Fixing the "There is already an open DataReader associated with this Command which must be closed first." exception in Entity Framework

下面代码可能会报如标题所示错误

var contacts = from c in db.Contact
select c; foreach (Contact c in contacts) {
if (c.Phones.IsLoaded == false)
c.Phones.Load(); if (c.Phones.Count > 0) {
foreach (ContactPhone p in c.Phones){
}
}
}

Tip: 真正执行查询是在foreach语句执行时才发生,在之前只是建立查询。

解决办法:

1,修改连接串,加上MultipleActiveResultSets=true

  <connectionStrings>
<add name="connectionStrings" connectionString="Data Source=(local);Initial Catalog=xxx;uid=xx;pwd=xx;MultipleActiveResultSets=true" providerName="System.Data.SqlClient"/>
</connectionStrings>

2, 一次性先把数据读出来

var contacts = from c in db.Contact
select c; List results = contacts.ToList(); foreach (Contact c in results){
}

提示:contacts.ToList() 的作用是强制加载contact列表,也就是先强制执行查询,再做后续处理。

原文:http://netknowledge.net/blogs/onmaterialize/archive/2006/09/20/Fixing-the-_2200_There-is-already-an-open-DataReader-associated-with-this-Command-which-must-be-closed-first_2E002200_-exception-in-Entity-Framework.aspx

关于 MultipleActiveResultSets

使用MultipleActiveResultSets复用Sql Server 2008数据库连接

分类: Sql Server 20082009-05-19 23:18 3225人阅读 评论(1) 收藏 举报

数据库sql serversecurityserversqlclass

MultipleActiveResultSets可以使数据库连接复用。这样就不怕数据库的连接资源被耗尽了。使用方法很简单,只需要把它加到数据的连接字符串中即可。

例如:server=(local);Integrated Security = true;database=AdventureWorks;MultipleActiveResultSets=true;

测试用例:

[c-sharp] view plaincopy

  1. using System; 
  2. using System.Threading; 
  3. using System.Data.SqlClient; 
  4. using System.Configuration; 
  5. namespace ConsoleApplication1 
  6. public class Example 
  7. public static void Main() 
  8. SqlConnection sql1 = new SqlConnection("server=(local);Integrated Security = true;database=AdventureWorks;"); 
  9. sql1.Open(); 
  10. SqlCommand comm1 = new SqlCommand(); 
  11. comm1.CommandText = "select 1"; 
  12. comm1.CommandType = System.Data.CommandType.Text; 
  13. comm1.Connection = sql1; 
  14. comm1.ExecuteNonQuery(); 
  15. sql1.Close(); 
  16. Console.ReadLine(); 
  17. }

编译后,打开bin/debug/ConsoleApplication1.exe。

在SQL Server 2008 Management Studio中打开一个新窗口,输入sp_who

按F5执行,可以发现已经有一个用户连接到AdventureWorks数据库了。

再打开一个ConsoleApplication1.exe,发现又会多一个用户连接到AdventureWorks数据库。

现在把程序的连接字符串改为server=(local);Integrated Security = true;database=AdventureWorks;MultipleActiveResultSets=true;

按上面的顺序执行,发现不管打开多少个ConsoleApplication1.exe,数据库中没有用户或只有一个用户连接着AdventureWorks数据库。

这就是数据库连接复用的好处了。

关于数据库连接字符串的其它用法,参见:

http://blog.csdn.net/tjvictor/archive/2009/03/19/4004277.aspx

MultipleActiveResultSets

ADO.NET 1.x 利用SqlDataReader读取数据,针对每个结果集需要一个独立的连接。当然,你还必须管理这些连接并且要付出相应的内存和潜在的应用程序中的高度拥挤的瓶颈代价-特别是在数据集中的Web应用程序中。

ADO.NET 2.的一个新特征多数据结果集(Multiple Active Result Sets,简称MARS)-它允许在单个连接上执行多重的数据库查询或存储过程。这样的结果是,你能够在单个连接上得到和管理多个、仅向前引用的、只读的结果集。目前实现这个功能的数据库只有Sql Server 2005。所以当我们针对Sql Sever 2005的时候,需要重新审视DataReader对象的使用。使用SqlServer 2005,可以在一个Command对象上同时打开多个DataReader,节约数据库联接所耗费的服务器资源,在实际开发中普遍存在的一种典型的从数据库中读写数据的情形是,你可以使用多重连接而现在只用一个连接就足够了。例如,如果你有一些来自于几个表中的数据-它们不能被联结到一个查询中,那么你就会有多重的连接-每个连接都有一个与之相关连的命令用于读取数据。同样,如果你正在向一个表写数据,那么你需要另外一个连接或连接集合-如果有多个表要被更新的话。

例如下面的代码

//MultipleActiveResultSets=true打开联接

string connstr = "server=(local);database=northwind;integrated security=true;MultipleActiveResultSets=true";

SqlConnection conn = new SqlConnection(connstr);
            conn.Open();
            SqlCommand cmd1 = new SqlCommand("select * from customers", conn);
            SqlCommand cmd2 = new SqlCommand("select * from orders", conn);
            SqlDataReader rdr1 = cmd1.ExecuteReader();
           // next statement causes an error prior to SQL Server 2005
            SqlDataReader rdr2 = cmd2.ExecuteReader();
           // now you can reader from rdr1 and rdr2 at the same time.

conn.Close();

http://www.cnblogs.com/RobotH/archive/2007/08/22/865942.html

http://www.cnblogs.com/season2009/archive/2012/12/25/2831863.html

http://blog.csdn.net/tjvictor/article/details/4202535

There is already an open DataReader associated with this Command which must be closed first." exception in Entity Framework的更多相关文章

  1. 在实体对象中访问导航属性里的属性值出现异常“There is already an open DataReader associated with this Command which must be closed first”

    在实体对象中访问导航属性里的属性值出现异常“There is already an open DataReader associated with this Command which must be ...

  2. 关于MultipleActiveResultSets属性导致的There is already an open DataReader associated with this Command which must be closed first的解决方法

    执行SqlDataReader.Read之后,如果还想用另一个SqlCommand执行Insert或者Update操作的话,会得到一个错误提示:There is already an open Dat ...

  3. 多线程下,多次操作数据库报错,There is already an open DataReader associated with this Command which must be closed first.

    原文:https://www.cnblogs.com/sdusrz/p/4433108.html 执行SqlDataReader.Read之后,如果还想用另一个SqlCommand执行Insert或者 ...

  4. error 'there is already an open datareader associated with this command which must be closed first'

    This can be easily solved by allowing MARS in your connection string. Add MultipleActiveResultSets=t ...

  5. There is already an open DataReader associated with this Command which must be closed first

    通常出现在嵌套查询数据库(比如在一个qry的遍历时,又进行了数据库查询) 通过在连接字符串中允许MARS可以轻松解决这个问题. 将MultipleActiveResultSets = true添加到连 ...

  6. There is already an open DataReader associated with this Connection which must be closed first

    使用MVC4 EF Linq获取foreach列表循环的时候遇到了如下的问题:报错提示 There is already an open DataReader associated with this ...

  7. C#.net mysql There is already an open datareader associated with this command引发的问题

    [参考]There is already an open datareader associated with this command引发的问题 我在语句中并未使用 DataReader,未何也提示 ...

  8. EF There is already an open DataReader associated with this Command

    捕捉到 System.InvalidOperationException _HResult=-2146233079 _message=意外的连接状态.在使用包装提供程序时,请确保在已包装的 DbCon ...

  9. Entity Framework "There is already an open DataReader associated with this 的解决办法

    解决办法: 1,修改连接串,加上MultipleActiveResultSets=true 2, 一次性先把数据读出来 var contacts = from c in db.Contact sele ...

随机推荐

  1. 入坑HttpServletRequest.getParameterMap

    在项目开发的时候遇到一个小坑,在发送了异步请求以后,回调的时候传递给我一个参数直接就是HttpServletRequest的请求,下面简称request: 在使用的时候自以为很简单,直接get就好了嘛 ...

  2. [css]需警惕CSS3属性的书写顺序

    转载张鑫旭:http://www.zhangxinxu.com/wordpress/2010/09/%E9%9C%80%E8%AD%A6%E6%83%95css3%E5%B1%9E%E6%80%A7% ...

  3. USACO2011Brownie Slicing巧克力蛋糕切片

    Description     Bessie烘焙了一块巧克力蛋糕.这块蛋糕是由R*C(1 <= R,C <= 500)个小的巧克力蛋糕组成的. 第i行,第j列的蛋糕有N_ij(1 < ...

  4. 在node.js中使用mongose模块

    对象与文档相对应 创建项目目录,用root进入 # mkdir /home/test/part9/ 直接# npm install mongoose,报错如下 ../node_modules/nan/ ...

  5. centos6.5安装sublime text 2

    今天在看ueillemmx的博客的时候,看到一神级编辑器,随即安装试了试,我了个去,果然好用,自动补全,自动对齐,样样精通啊! 下面是根据ueillemmx的步骤在CentOS上安装Sublime的过 ...

  6. Linux系统资源监控命令

    转自http://www.51testing.com/html/16/271416-149128.html 衡量CPU性能的指标: 1,用户使用CPU的情况:CPU运行常规用户进程CPU运行niced ...

  7. C语言->实验室->指针数组

    一 分析 讨论指针数组要从三个层面来考虑: 1)指针数组本身是什么 2)指针数组作为参数时的表现 3)指针数组作为返回值时的表现 二 指针数组是什么 1)指针数组--指针的集合 数组是若干元素的集合, ...

  8. Objective-C( Foundation框架 一 数组(NSMutableArray))

    NSMutableArray:可变数组 NSMutableArray是NSArray的子类 创建NSMutableArray数组对象 添加数组元素: // 创建数组 NSMutableArray *a ...

  9. iOS 通过 JSPatch 实时修复线上 bug!

    JSPatch 是一个开源项目(Github链接),只需要在项目里引入极小的引擎文件,就可以使用 JavaScript 调用任何 Objective-C 的原生接口,替换任意 Objective-C ...

  10. debug实战:COM组件GetToSTA导致高内存+GC被阻塞

    最近花了好几周解决一个WPF高内存的问题,问题的表象是内存不断增加.未被回收,根源是GC的FinalizeThread被阻塞,导致整个GC挂掉.从以下几步来分析这个问题: 1.用ANTS Memory ...