使用WebContext.Items 存储Linq to sql 的DataContext实例引发"InvalidCastException"错误

     为了保证在一次请求过程中, 使用同一个DataContext实例, 我们项目使用WebContext.items 来存储这个实例.

     最近不知道怎么回事, 总是偶然性的抛出下面这个类型转换失败错误, 百思不得其解, 最后在MSDN的一个帖子里找到一种解释: 数据库没有关闭,引发这个错误!建议使用using 块来建立DataContext对象。但是由于使用了WebContext.Items来存储,不可能使用using 块,不得已, 做了个HttpModule来解决这个问题,在每次RequestEnd中关闭连接。 如今一周过去了,这个错误没有再发生。

Event code: 3005
Event message: An unhandled exception has occurred.
Event time: 9/17/2012 9:43:46 AM
Event time (UTC): 9/17/2012 6:43:46 AM
Event ID: 45cb065c6d3f42d6b4b030f1cee291a9
Event sequence: 23723
Event occurrence: 252
Event detail code: 0
Application information:
Application domain: /LM/W3SVC/2/ROOT-1-129923217234789546
Trust level: Full
Application Virtual Path: /
Application Path: C:\PublicWebs\Tekian\
Machine name: U1W1
Process information:
Process ID: 6812
Process name: w3wp.exe
Account name: TEKIAN\mce application
Exception information:
Exception type: InvalidCastException
Exception message: Specified cast is not valid.
Request information:
Request URL:
https://u1a.manuonline.com/default.aspx
Request path: /default.aspx
User host address: 83.241.243.7
User: TEKIAN\
Is authenticated: True
Authentication Type: Basic
Thread account name: TEKIAN\mce application
Thread information:
Thread ID: 13
Thread account name: TEKIAN\mce application
Is impersonating: False
Stack trace: at System.Data.Linq.SqlClient.SqlProvider.Execute(Expression query, QueryInfo queryInfo, IObjectReaderFactory factory, Object[] parentArgs, Object[] userArgs, ICompiledSubQuery[] subQueries, Object lastResult)
at System.Data.Linq.SqlClient.SqlProvider.ExecuteAll(Expression query, QueryInfo[] queryInfos, IObjectReaderFactory factory, Object[] userArguments, ICompiledSubQuery[] subQueries)
at System.Data.Linq.SqlClient.SqlProvider.System.Data.Linq.Provider.IProvider.Execute(Expression query)
at System.Data.Linq.Table`1.System.Linq.IQueryProvider.Execute[TResult](Expression expression)
at System.Linq.Queryable.Any[TSource](IQueryable`1 source, Expression`1 predicate)
at DataAccessService.IsLegacy(String userId, String dbName)
at Helper.IsLegacy(String userId, String company)
at Helper.IsLegacy()
at _Default.Page_Load(Object sender, EventArgs e)
at System.Web.UI.Control.OnLoad(EventArgs e)
at ManuPageBase.OnLoad(EventArgs e)
at System.Web.UI.Control.LoadRecursive()
at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
原文地址:https://www.cnblogs.com/Hcsdn/p/2716874.html