您的位置:首页 > 其它

EntityFramework4.0中遇到New transaction is not allowed because there are other threads running in the session

2011-03-22 15:08 736 查看
在使用EntityFramework4.0时,我们遇到这样的Exception:Newtransactionisnotallowedbecausethereareotherthreadsrunninginthesession,是在这样的场景下面:

[Test]
[ExpectedException(typeof(System.Data.EntityException))]
publicvoidTestUnknowIssue2()
{
using(vardb=newTestPerformaceDBEntities())
{
varproducts=db.Products.Where(p=>p.CategoryID==1);
foreach(varproductinproducts)
{
Debug.WriteLine("Getit");
product.ProductName="newname";
//Herewillthrow:Newtransactionisnotallowedbecausethereareotherthreadsrunninginthesession.
db.SaveChanges();
}
}
}

.csharpcode,.csharpcodepre
{
font-size:small;
color:black;
font-family:consolas,"CourierNew",courier,monospace;
background-color:#ffffff;
/*white-space:pre;*/
}
.csharpcodepre{margin:0em;}
.csharpcode.rem{color:#008000;}
.csharpcode.kwrd{color:#0000ff;}
.csharpcode.str{color:#006080;}
.csharpcode.op{color:#0000c0;}
.csharpcode.preproc{color:#cc6633;}
.csharpcode.asp{background-color:#ffff00;}
.csharpcode.html{color:#800000;}
.csharpcode.attr{color:#ff0000;}
.csharpcode.alt
{
background-color:#f4f4f4;
width:100%;
margin:0em;
}
.csharpcode.lnum{color:#606060;}

我们使用是Northwind示例Database,你注意要上面代码中有foreach。主要原因是我们的foreach的循环时,我们不能在同一个连接中同时Reader读数据,又同时做Update,它还没有读完。这时你需要把这个集合对象转换成Array或List<T>,将代码修改为这样就可以了:

[Test]
publicvoidTestUnknowIssue2()
{
using(vardb=newTestPerformaceDBEntities())
{
varproducts=db.Products.Where(p=>p.CategoryID==1).ToList();
foreach(varproductinproducts)
{
Debug.WriteLine("Getit");
product.ProductName="newname";
db.SaveChanges();
}
}
}

.csharpcode,.csharpcodepre
{
font-size:small;
color:black;
font-family:consolas,"CourierNew",courier,monospace;
background-color:#ffffff;
/*white-space:pre;*/
}
.csharpcodepre{margin:0em;}
.csharpcode.rem{color:#008000;}
.csharpcode.kwrd{color:#0000ff;}
.csharpcode.str{color:#006080;}
.csharpcode.op{color:#0000c0;}
.csharpcode.preproc{color:#cc6633;}
.csharpcode.asp{background-color:#ffff00;}
.csharpcode.html{color:#800000;}
.csharpcode.attr{color:#ff0000;}
.csharpcode.alt
{
background-color:#f4f4f4;
width:100%;
margin:0em;
}
.csharpcode.lnum{color:#606060;}

注意返回的数量很大时,类似填充List方法将会消耗很多内存。此时,建议你使用skip方式对结果集进行数据分页处理。关于Linq中的数据分页你可参考这篇POST.

希望对您开发有帮助。

作者:PetterLiu
出处:http://www.cnblogs.com/wintersun/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
该文章也同时发布在我的独立博客中-PetterLiuBlog。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐