实体框架删除子对象 [英] Entity Framework delete child object

查看:122
本文介绍了实体框架删除子对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经没有任何级联删除两个表。我想删除父对象,所有子对象。我这样做,这样

  //获取父对象
返回_dataContext.Menu.Include(ChildMenu)包含(ParentMenu)包含(图片)FirstOrDefault(M => m.MenuId ==标识)。;
//然后我循环所有子对象
VAR picList =(列表<图片和GT;)menu.Pictures.ToList();的for(int i = 0; I< picList.Count;我++)
 {
  如果(File.Exists(HttpContext.Current.Server.MapPath(picList [I] .ImgPath)))
  {
     File.Delete(HttpContext.Current.Server.MapPath(picList [I] .ImgPath));
  }
  如果(File.Exists(HttpContext.Current.Server.MapPath(picList [I] .ThumbPath)))
  {
     File.Delete(HttpContext.Current.Server.MapPath(picList [I] .ThumbPath));
  }  // **什么,我必须在这里做?**
  //menu.Pictures.Remove(picList[i]);
  // DataManager的DM =新的DataManager();
  // dm.Picture.Delete(picList [I] .ID);  //menu.Pictures.de
  // _ dataContext.SaveChanges();
  // picList [我] = NULL;}//删除父对象
_dataContext.DeleteObject(_dataContext.Menu.Include(ChildMenu)。包括(ParentMenu)
    .INCLUDE(图片)FirstOrDefault(M = GT; m.MenuId == ID););
_dataContext.SaveChanges();


解决方案

这足以将

 < OnDelete行动=级联/>  

的CSDL部分该模型。

在这种情况下,您的code会工作。

I have two tables without any cascade deleting. I want to delete parent object with all child objects. I do it this way

//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();

解决方案

It is enough to set the

<OnDelete Action="Cascade" />

for the master association end in the CSDL part of the model.
In this case your code will work.

这篇关于实体框架删除子对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆