2013-06-26 48 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) 
{ 
} 

問題已解決。

謝謝您的回答...