2013-06-26 45 views
0

当我运行这段代码它说:实体框架4.1语境中扩展方法

Store update, insert, or delete statement affected an unexpected number of rows (0). Entities may have been modified or deleted since entities were loaded. Refresh ObjectStateManager entries. 

我能想象这里的情况。大概是因为这个:

//Default.aspx.cs 
MyEntity cont = new MyEntity(); 
IEnumerable<Product> p = from c in cont.Products.AsEnumerable() 
       select c; 
Product example = p.ToArray()[0]; 
example.Delete(); // This Delete method is an extension method which you'll see in below. 
//I also have some other stuff like 

IEnumerable<Category> cc = from n in cont.Categories.AsEnumerable() 
           select n; 
cont.Categories.Remove(cc.ToArray()[0]); 
cont.SaveChanges(); //throws the error 

这里是扩展方法

public static bool Delete(this Product pro,bool SetNull = false) { 
    using (var en = new MyEntity()) { 
     IEnumerable<Product> s = from ss in en.Products 
           where ss.ID == pro.ID 
           select ss; 

     en.Products.Remove(s.SingleOrDefault()); 
     en.SaveChanges(); 
    } 
} 

的扩展方法工作的主要部分,实体从数据库中删除。但当程序来到

cont.SaveChanges(); 

行,它会引发错误。我认为,这个错误出现了,因为我使用另一个MyEntity()类更改了另一个方法中的实体。所以我已经寻找一种方法来刷新另一个。但我不能...

+0

我很好奇 - 我的答案是否解决了您的问题? –

回答

4

我认为你应该将上下文作为参数传递给删除方法。 不要在方法中构造新的上下文,并从中删除 - 而是从原始上下文中删除。

+0

'新的交易是不允许的,因为会话中有其他线程正在运行。' 这一次,这个错误出现了...... – paroxit

0

我想通过使用奥默尔施莱弗的建议,以及我在另一个主题上发现的东西。

New transaction is not allowed because there are other threads running in the session LINQ To Entity

我使用的上下文关系中删除方法的参数,但它引发的错误

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

然后,我改变了for循环,我使用,这样

foreach (Product m in p.ToList()) 
{ 
} 

而不是此

foreach (Product m in p) 
{ 
} 

问题已解决。

谢谢您的回答...