简体   繁体   中英

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. I'd normally hand crank this stuff but I'm investigation increasing productivity.

I have the following providing JSON to my knockout model.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM