< 2025年2月 >
26 27 28 29 30 31 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 1
2 3 4 5 6 7 8

        在使用Entity Framework 4.0时,我们遇到这样的Exception: New transaction is not allowed because there are other threads running in the session,是在这样的场景下面:

   1:          [Test]
   2:          [ExpectedException(typeof(System.Data.EntityException))]
   3:          public void TestUnknowIssue2()
   4:          {
   5:              using (var db = new TestPerformaceDBEntities())
   6:              {
   7:                  var products = db.Products.Where(p => p.CategoryID == 1);   
   8:                  foreach (var product in products)
   9:                  {
  10:                      Debug.WriteLine("Get it");
  11:   
  12:                      product.ProductName = "new name";
  13:   
  14:                      //Here will throw :New transaction is not allowed because there are other threads running in the session.
  15:                      db.SaveChanges();
  16:                  }
  17:              }
  18:          }

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

   1:          [Test]
   2:          public void TestUnknowIssue2()
   3:          {
   4:              using (var db = new TestPerformaceDBEntities())
   5:              {
   6:                  var products = db.Products.Where(p => p.CategoryID == 1).ToList();   
   7:                  foreach (var product in products)
   8:                  {
   9:                      Debug.WriteLine("Get it");
  10:   
  11:                      product.ProductName = "new name";
  12:                      db.SaveChanges();
  13:                  }
  14:              }
  15:          }

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

        希望对您开发有帮助。


作者:Petter Liu
出处:http://www.cnblogs.com/wintersun/
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
该文章也同时发布在我的独立博客中-Petter Liu Blog

posted on   PetterLiu  阅读(3185)  评论(1编辑  收藏  举报
编辑推荐:
· [.NET]调用本地 Deepseek 模型
· 一个费力不讨好的项目,让我损失了近一半的绩效!
· .NET Core 托管堆内存泄露/CPU异常的常见思路
· PostgreSQL 和 SQL Server 在统计信息维护中的关键差异
· C++代码改造为UTF-8编码问题的总结
阅读排行:
· 实操Deepseek接入个人知识库
· CSnakes vs Python.NET:高效嵌入与灵活互通的跨语言方案对比
· 【.NET】调用本地 Deepseek 模型
· Plotly.NET 一个为 .NET 打造的强大开源交互式图表库
· 上周热点回顾(2.17-2.23)
历史上的今天:
2009-03-22 用反射判断一个类型是否是Nullable同时获取它的根类型
点击右上角即可分享
微信分享提示