There is already an open DataReader associated with this Command which must be closed first." exception in Entity Framework
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列表,也就是先强制执行查询,再做后续处理。
使用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
- using System;
- using System.Threading;
- using System.Data.SqlClient;
- using System.Configuration;
- namespace ConsoleApplication1
- {
- public class Example
- {
- public static void Main()
- {
- SqlConnection sql1 = new SqlConnection("server=(local);Integrated Security = true;database=AdventureWorks;");
- sql1.Open();
- SqlCommand comm1 = new SqlCommand();
- comm1.CommandText = "select 1";
- comm1.CommandType = System.Data.CommandType.Text;
- comm1.Connection = sql1;
- comm1.ExecuteNonQuery();
- sql1.Close();
- Console.ReadLine();
- }
- }
- }
编译后,打开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的更多相关文章
- 在实体对象中访问导航属性里的属性值出现异常“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 ...
- 关于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 ...
- 多线程下,多次操作数据库报错,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或者 ...
- 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 ...
- There is already an open DataReader associated with this Command which must be closed first
通常出现在嵌套查询数据库(比如在一个qry的遍历时,又进行了数据库查询) 通过在连接字符串中允许MARS可以轻松解决这个问题. 将MultipleActiveResultSets = true添加到连 ...
- 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 ...
- C#.net mysql There is already an open datareader associated with this command引发的问题
[参考]There is already an open datareader associated with this command引发的问题 我在语句中并未使用 DataReader,未何也提示 ...
- EF There is already an open DataReader associated with this Command
捕捉到 System.InvalidOperationException _HResult=-2146233079 _message=意外的连接状态.在使用包装提供程序时,请确保在已包装的 DbCon ...
- Entity Framework "There is already an open DataReader associated with this 的解决办法
解决办法: 1,修改连接串,加上MultipleActiveResultSets=true 2, 一次性先把数据读出来 var contacts = from c in db.Contact sele ...
随机推荐
- 经典SQL语句大全以及50个常用的sql语句
经典SQL语句大全 一.基础 1.说明:创建数据库CREATE DATABASE database-name 2.说明:删除数据库drop database dbname3.说明:备份sql serv ...
- 饮水思源——python中常用基础类源码解析
1.bool类 2.int类 3.long类 4.float类 5.str类 6.list类 7.tuple类 8.dict类 9.collections类 Counter类:为hashable对象计 ...
- div被object覆盖的解决办法
代码: <div id="contextmenu" style="width: 120px; height:120px;DISPLAY: none; top: 26 ...
- Project中分清楚挣值项
在项目管理非常重要的挣值管理,有一些关键项,像PV,EV,AC,BAC,EAC,ETC等等这些都是关键项,如果这个没分清楚,计算出很多东西都是错的,下面两个图是我一个项目快要完成的报表. 图1 图2 ...
- investopedia level 2
Mispricing can be explained by the sum of the two components: true mispricing and estimation errorVe ...
- hdu 1032
题目的意思是把输入的i,j 从i到j的每一个数 做循环,输出循环次数最大的值 易错的地方:做循环是容易直接用i进行计算 i=i/2:或i=i*3+1: 这样i的值改变就不能在做下面数的循环 #incl ...
- iOS开发UI篇—使用xib自定义UItableviewcell实现一个简单的团购应用界面布局
iOS开发UI篇—使用xib自定义UItableviewcell实现一个简单的团购应用界面布局 一.项目文件结构和plist文件 二.实现效果 三.代码示例 1.没有使用配套的类,而是直接使用xib文 ...
- Positive-definite kernel
Definition Let be a sequence of (complex) Hilbert spaces and be the bounded operators from Hi to Hj. ...
- Android RecyclerView 使用完全解析
概述 RecyclerView出现已经有一段时间了,相信大家肯定不陌生了,大家可以通过导入support-v7对其进行使用. 据官方的介绍,该控件用于在有限的窗口中展示大量数据集,其实这样功能的控件我 ...
- Hadoop 2.2.0学习笔记20131209
1.下载java 7并安装 [root@server- ~]# rpm -ivh jdk-7u40-linux-x64.rpm Preparing... ####################### ...