实体框架删除子对象

kus*_*agi 2 asp.net entity-framework object

我有两个没有任何级联删除的表.我想删除所有子对象的父对象.我是这样做的

//get parent object
return _dataContext.Menu.Include("ChildMenu").Include("ParentMenu").Include("Pictures").FirstOrDefault(m => m.MenuId == id);
//then i loop all child objects
var picList = (List<Picture>)menu.Pictures.ToList();

for (int i = 0; i < picList.Count; i++)
 {
  if (File.Exists(HttpContext.Current.Server.MapPath(picList[i].ImgPath)))
  {
     File.Delete(HttpContext.Current.Server.MapPath(picList[i].ImgPath));
  }
  if (File.Exists(HttpContext.Current.Server.MapPath(picList[i].ThumbPath)))
  {
     File.Delete(HttpContext.Current.Server.MapPath(picList[i].ThumbPath));
  }

  //**what must i do here?**
  //menu.Pictures.Remove(picList[i]);
  //                DataManager dm = new DataManager();
  //                dm.Picture.Delete(picList[i].Id);

  //menu.Pictures.de
  //_dataContext.SaveChanges();
  //picList[i] = null;

}

//delete parent object
_dataContext.DeleteObject(_dataContext.Menu.Include("ChildMenu").Include("ParentMenu")
    .Include("Pictures").FirstOrDefault(m => m.MenuId == id););
_dataContext.SaveChanges();
Run Code Online (Sandbox Code Playgroud)

Dev*_*art 5

这足以设定

<OnDelete Action="Cascade" />
Run Code Online (Sandbox Code Playgroud)对于主协会在模型的CSDL部分结束.
在这种情况下,您的代码将起作用.

  • 还不够.您需要1)加载所有相关实体或2)在DB中具有级联. (3认同)