实体框架:已经有一个与此命令关联的打开的 DataReader [英] Entity Framework: There is already an open DataReader associated with this Command

查看:33
本文介绍了实体框架:已经有一个与此命令关联的打开的 DataReader的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用实体框架,偶尔会出现此错误.

I am using Entity Framework and occasionally i will get this error.

EntityCommandExecutionException
{"There is already an open DataReader associated with this Command which must be closed first."}
   at System.Data.EntityClient.EntityCommandDefinition.ExecuteStoreCommands...

即使我没有进行任何手动连接管理.

Even though i am not doing any manual connection management.

此错误间歇性发生.

触发错误的代码(为了便于阅读而缩短):

code that triggers the error (shortened for ease of reading):

        if (critera.FromDate > x) {
            t= _tEntitites.T.Where(predicate).ToList();
        }
        else {
            t= new List<T>(_tEntitites.TA.Where(historicPredicate).ToList());
        }

使用 Dispose 模式以便每次打开新连接.

using Dispose pattern in order to open new connection every time.

using (_tEntitites = new TEntities(GetEntityConnection())) {

    if (critera.FromDate > x) {
        t= _tEntitites.T.Where(predicate).ToList();
    }
    else {
        t= new List<T>(_tEntitites.TA.Where(historicPredicate).ToList());
    }

}

还是有问题

如果连接已经打开,为什么 EF 不重用它.

why wouldn't EF reuse a connection if it is already open.

推荐答案

这与关闭连接无关.EF 正确管理连接.我对这个问题的理解是,有多个数据检索命令在单个连接(或具有多个选择的单个命令)上执行,而下一个 DataReader 在第一个完成读取之前执行.避免异常的唯一方法是允许多个嵌套的 DataReaders = 打开 MultipleActiveResultSets.另一种总是发生这种情况的情况是,当您遍历查询结果 (IQueryable) 时,您将在迭代中触发加载实体的延迟加载.

It is not about closing connection. EF manages connection correctly. My understanding of this problem is that there are multiple data retrieval commands executed on single connection (or single command with multiple selects) while next DataReader is executed before first one has completed the reading. The only way to avoid the exception is to allow multiple nested DataReaders = turn on MultipleActiveResultSets. Another scenario when this always happens is when you iterate through result of the query (IQueryable) and you will trigger lazy loading for loaded entity inside the iteration.

这篇关于实体框架:已经有一个与此命令关联的打开的 DataReader的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆