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列表,也就是先强制执行查询,再做后续处理。
签名:删除冗余的代码最开心,找不到删除的代码最痛苦!
浙公网安备 33010602011771号