当我运行这段代码时,它说:
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();
line ,它会引发错误。我认为,出现此错误是因为我使用另一个 MyEntity() 类更改了另一个方法中的实体。所以我一直在寻找一种方法来刷新另一个。但我不能...