【发布时间】:2014-09-23 22:56:07
【问题描述】:
我遇到了一个非常奇怪的 Cast Exception。异常发生非常罕见。
这是代码:
protected Guid GetWebsiteLanguage(Guid websiteId, int languageId)
{
Guid websiteLanguagesId = Guid.Empty;
var websites = from item in DataContext.WebsiteLanguages
where item.WebsiteId == websiteId && item.LanguageId == languageId
select item.Id;
if (websites.Count() != 1)
throw new ArgumentException("Wrong channel parameters.");
try
{
websiteLanguagesId = websites.First();
}
catch (Exception ex)
{
string errorMessage = websites.First() == null ? "websites.First() is null" : string.Concat("Invalid Guid ", websites.First().ToString());
throw new Exception(string.Concat(ex.Message, " - Log: ", errorMessage, " - Variables: websiteId = ", websiteId.ToString(), " languageId = ", languageId));
}
return websiteLanguagesId;
}
我得到的例外是:
指定的演员表无效。 - 日志:
无效的指导 ef058612-37db-4b02-aa13-5a528819a5e0
变量: websiteId = db725f45-70fa-4fd0-b344-55bbf17a5c15
语言 ID = 2057
这是 catch 异常的输出。如您所见,我们有一个 GUID,但他仍然给出了强制转换异常......
有时它会在这个函数的 Count() 上出错。然后这是堆栈跟踪:
System.Data.Linq.IExecuteResult 执行(System.Linq.Expressions.Expression,QueryInfo,System.Data.Linq.SqlClient.IObjectReaderFactory,System.Object[],System.Object[],System.Data.Linq。 SqlClient.ICompiledSubQuery[], System.Object)STACKTRACE: 在 System.Data.Linq.SqlClient.SqlProvider.Execute(Expression query, QueryInfo queryInfo, IObjectReaderFactory factory, Object[] parentArgs, Object[] userArgs, ICompiledSubQuery[] subQueries, Object最后一个结果)
在 System.Data.Linq.SqlClient.SqlProvider.ExecuteAll(表达式查询,QueryInfo[] queryInfos,IObjectReaderFactory 工厂,Object[] userArguments,ICompiledSubQuery[] subQueries)
在 System.Data.Linq.SqlClient.SqlProvider.System.Data.Linq.Provider.IProvider.Execute(表达式查询)
在 System.Data.Linq.DataQuery1.System.Linq.IQueryProvider.Execute[S](Expression expression)
at System.Linq.Queryable.Count[TSource](IQueryable1 来源)
在 GetWebsiteLanguage(Guid websiteId, Int32 languageId)
当这种情况发生时,唯一的解决方案是进行 iis 应用程序池回收,它会再次运行。
有什么想法吗?
这就是我处理数据上下文的方式
public MyDataContext DataContext
{
get
{
//Changed this to make this testable with unit tests
if (HttpContext.Current != null)
{
if (!HttpContext.Current.Items.Contains(DataContextKey))
HttpContext.Current.Items.Add(DataContextKey, new MyDataContext(ConnectionString));
return (MyDataContext)HttpContext.Current.Items[DataContextKey];
}
else
{
//When context is not available
if (context == null)
context = new MyDataContext(ConnectionString);
return context;
}
}
}
【问题讨论】:
标签: linq-to-sql guid .net