當我運行這段代碼它說:實體框架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()類更改了另一個方法中的實體。所以我已經尋找一種方法來刷新另一個。但我不能...
我很好奇 - 我的答案是否解決了您的問題? –