c# – 同时调用ASP.NET托管的WCF服务时的实体框架错误
发布时间:2020-12-15 17:28:40 所属栏目:百科 来源:网络整理
导读:我有一个简单的ASP.NET托管WCF服务,它有几个方法在使用实体框架时都具有相同的模式… public void Operation1(string username){ using(MyEFContext context = new MyEFContext()) { UserInfo info = (from ui in context.UserInfos where ui.User.Equals(us
我有一个简单的ASP.NET托管WCF服务,它有几个方法在使用实体框架时都具有相同的模式…
public void Operation1(string username) { using(MyEFContext context = new MyEFContext()) { UserInfo info = (from ui in context.UserInfos where ui.User.Equals(username) select ui).FirstOrDefault<UserInfo >(); info.LastAccess = DateTime.Now; // Operation specific code,such as getting information using the EF context context.SaveChanges(); } } 这是一个简化版本,以保持示例简单,但即使这个简单版本与我的生产代码集具有相同的错误.代码首先使用实体??框架获取用户信息,更新用户LastAccess字段,然后执行特定于操作的代码.特定于操作的代码只是查询信息.最后它调用SaveChanges,以便将LastAccess保存回数据库.现在这一切都完美无缺,直到我的客户端并行进行两次调用. 客户端进行两次调用,每次调用进行不同的操作,但它们都具有与上面相同的代码模式.有时两个电话都会成功完成.但有时其中一个会产生错误,它可能是以下三个中的任何一个…… System.Data.EntityException: The underlying provider failed on Open. ---> System.InvalidOperationException: The connection was not closed. The connection^s current state is connecting. System.Data.EntityCommandExecutionException: An error occurred while executing the command definition. See the inner exception for details. ---> System.InvalidOperationException: ExecuteReader requires an open and available Connection. The connection^s current state is closed. System.InvalidOperationException: Invalid attempt to read when no data is present. 很明显,我对EF和ASP.NET的理解是有缺陷的,因为我预计这两个操作甚至可以并行工作.我是否需要锁定每个方法,以便它们一次只能出现一个?当然不是.有任何想法吗? 解决方法
在这里找到答案
Managing EntityConnection lifetime.事实证明,为我的所有上下文重用相同的EntityConnection实例是个问题.所以现在我每次都要创建一个新的.
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |