C# 不允许新事务,因为会话 LINQ To Entity 中有其他线程正在运行
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10096509/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
New transaction is not allowed because there are other threads running in the session LINQ To Entity
提问by Nick LaMarca
Any ideas on why this could be breaking?
关于为什么这可能会中断的任何想法?
foreach (var p in pp)
{
ProjectFiles projectFile = (ProjectFiles)p;
projectFile.Status = Constants.ProjectFiles_ERROR;
projectFile.DateLastUpdated = DateTime.Now;
context.SaveChanges();
}
I read that the workaround the issue, is to retrieve the results in one go before the foreach loop.
我读到该问题的解决方法是在 foreach 循环之前一次性检索结果。
But didnt I do that? "pp" is the collection of results in my case
但我不是这样做的吗?“pp”是我案例中的结果集合
采纳答案by Guffa
The ppvariable isn't a collection of objects, it's an enumerator that can return objects. While you use the enumerator, the source has to remain open.
该pp变量不是对象的集合,它是一个枚举,可以返回的对象。使用枚举器时,源必须保持打开状态。
Use the ToListmethod to realise the enumerator into a collection. That will read all items from the enumerator and close the connection to the source, so that you can use the connection for other things.
使用该ToList方法将枚举器实现为集合。这将从枚举器中读取所有项目并关闭与源的连接,以便您可以将连接用于其他事情。
foreach (var p in pp.ToList())
回答by Captain Kenpachi
What's happening is that you're using one SQL connection to iterate over a collection of DB entities, then using another connection to save changes. This happens because your classes are basically "married" to one instance of your db connection and cannot be changed by another.
发生的情况是您使用一个 SQL 连接来迭代一组数据库实体,然后使用另一个连接来保存更改。发生这种情况是因为您的类基本上与数据库连接的一个实例“结合”,并且不能被另一个实例更改。
A way to get around this is to call .ToList()on your collection before iterating it.
解决此问题的一种方法是.ToList()在迭代之前调用您的集合。
And while you're at it, call context.SaveChanges()only once after the loop exits to speed up the code.
并且,当您使用它时,context.SaveChanges()在循环退出后仅调用一次以加速代码。

