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

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

问题描述

我正在使用Entity Framework,偶尔会收到这个错误。

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.

此错误间歇性发生。

触发错误的代码(缩短阅读容易): p>

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已经打开,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天全站免登陆