尝试在删除操作中从obj A中删除B的ICollection,但得到此错误:
“错误DELETE语句与REFERENCE约束”
冲突有道理,但我不知道如何首先删除包含的Bs的ICollection,或者认为它们会被自动删除:
public ActionResult DeleteConfirmed(int id)
{
A objA = db.As.Find(id);
// **NOTE:** objA has a ICollection of objB's here that I tried to iterate and
// delete them here using: foreach (var i in A.Bs) {db.Bs.Remove(i);} : didn't work
db.As.Remove(objA);
db.SaveChanges();
return RedirectToAction("Index");
}
答案 0 :(得分:1)
在数据库中,您需要编辑外键约束并指定DELETE CASCADE选项,以便在删除该对象时也删除其所有引用。
答案 1 :(得分:1)
我同意Hasan的观点 - 只是提供了更多针对Entity Framework的信息,因为那里标记了这些信息。
注意实体框架的具体行为:
http://blogs.msdn.com/b/alexj/archive/2009/08/19/tip-33-how-cascade-delete-really-works-in-ef.aspx
If you add an Cascade delete rule to the model, you MUST have a corresponding DELETE rule in the database. If you absolutely insist on breaking rule (1) for some reason, Cascade will only work if you have all the dependents loaded in memory. (2) is *not* recommended!!!
另外 Problem with cascade delete using Entity Framework and System.Data.SQLite
答案 2 :(得分:0)
public ActionResult DeleteConfirmed(int id)
{
A objA = db.As.Find(id);
objA.Bs.Clear();
db.As.Remove(objA);
db.SaveChanges();
return RedirectToAction("Index");
}