Question

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;
}
1
0
2/6/2014 6:18:14 AM

Accepted Answer

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.

0
2/5/2014 9:53:44 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow