微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

c# – 同时调用ASP.NET托管的WCF服务时的实体框架错误

我有一个简单的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 @R_492_4045@ion 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实例是个问题.所以现在我每次都要创建一个新的.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐