[英]Deleting child objects with EF6
I'm new to EF6, its a side project for me and I'm struggling to see how to delete / modify child rows. 我是EF6的新手,它对我来说是一个辅助项目,我正努力查看如何删除/修改子行。 I'd normally hand crank this stuff but I'm investigation increasing productivity. 我通常会用手摇动这些东西,但是我正在调查以提高生产率。
I have the following providing JSON to my knockout model. 我有以下内容为我的淘汰赛模型提供JSON。
public JsonResult DetailsData(int? id)
{
var result = from p in db.People
where p.Id == id
select new
{
p.Id,
p.FirstName,
p.SecondName,
SicknessRecords = from s in p.SicknessRecords
select new
{
s.Id,
s.Description,
s.Occurred,
s.PersonId
}
};
return Json(result.First(), JsonRequestBehavior.AllowGet);
}
And then the following receiving it after it's been edited. 然后下面的内容在经过编辑后会收到。
[HttpPost]
public JsonResult DetailsData(Person model)
{
if (ModelState.IsValid)
{ //db.SaveChanges();
}
return null;
}
Inside the browser I've deleted the two child sickness rows, this is being correctly sent back to the server but I can't figure out how to delete them. 在浏览器中,我删除了两个儿童疾病行,这些行已正确发送回服务器,但是我不知道如何删除它们。
Update: 更新:
[HttpPost]
public JsonResult DetailsData(Person model)
{
if (ModelState.IsValid)
{
var item = (from p in db.People
where p.Id == model.Id
select p).First();
var removedRecords = item.SicknessRecords.Except(model.SicknessRecords).ToList();
foreach (var record in removedRecords)
{
item.SicknessRecords.Remove(record);
}
db.SaveChanges();
}
return null;
}
You have know what changed, which means you have to select the original person from the database anew. 您已经知道更改了什么,这意味着您必须从数据库中重新选择原始人员。 Then you can just do: 然后,您可以执行以下操作:
var removedRecords = person.SicknessRecords.Except(model.SicknessRecords);
for (var record in removedRecords)
{
person.SicknessRecords.Remove(record);
}
You should always modify the original record with the posted data, rather than just simply saving the posted data directly. 您应该始终使用发布的数据来修改原始记录,而不是简单地直接保存发布的数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.