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 

 

posted @ 2012-12-25 09:50 Season2009 阅读(...) 评论(...) 编辑 收藏