Linq“其他线程正在运行"错误 [英] Linq "other thread running" error

查看:70
本文介绍了Linq“其他线程正在运行"错误的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

public static bool DeleteAll()
        {
            try
            {
                Entities db = new Entities();
                IEnumerable<CMPS285_table_schedule> temp = (from p in db.CMPS285_table_schedule select p);
                foreach (CMPS285_table_schedule item in temp)
                {
                    db.DeleteObject(item);
                    db.SaveChanges();
                }
            }
            catch (Exception E)
            {
                Console.WriteLine(E);
            }
            
            return false;
        }


我收到错误消息:


I am getting the error:

"New transaction is not allowed because there are other threads running in the session."



需要帮助.



Need help.

推荐答案

public static bool DeleteAll()
        {
            try
            {
                using (Entities db = new Entities())
                {
                   var temp = (from p in db.CMPS285_table_schedule select p).ToList();
                   foreach (var item in temp)
                   {
                      db.DeleteObject(item);
                      db.SaveChanges();
                   }
                }
            }
            catch (Exception E)
            {
                Console.WriteLine(E);
            }
            
            return false;
        }



EF仍在原始事务中以检索表中的所有数据记录.因此,当我们调用.SaveChanges()在另一个事务中执行SQL语句时,我们会收到异常.

要解决此问题,建议您在foreach循环之前一口气检索结果.

另外,请查看下面有关延迟执行和立即执行的链接.
http://www.dotnetcurry.com/ShowArticle.aspx?ID=750 [ ^ ]
请投票并标记为解决方案谢谢.



EF is still in the original transaction to retrieve all the data records in Table. So when we call .SaveChanges() to execute the SQL statements in another transaction, we receive the exception.

To workaround the issue, I would recommend you retrieve the results in one go before the foreach loop.

Also please take a look at this link below on deferred and immediate execution.
http://www.dotnetcurry.com/ShowArticle.aspx?ID=750[^]
Please vote and mark as solution thanks.


只想补充一下我如何解决它.
要删除或添加的项目应作为参数/引用传递-在我看来,这就是问题所在.我将一个对象传递给delete方法,并尝试将其删除-错误.然后我创建了一个具有相同参数的对象并将其删除.欢呼!!!与上述相同的方法有效.

而不是无可挑剔的bla var.我只是不知道为什么,但是它有效
Just wanted to add how i fixed it.
items to delete or add should be passed as parameter/reference - in my case it was the problem. I passed an object to the delete method and tried to delete it - ERROR. then I created an object with same parameter and deleted it. HURRAY!!! the same method as above worked.

instead of Ieneurable bla blah var is preffered. I just dont know why but it works


这篇关于Linq“其他线程正在运行"错误的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆