I have a one to many relationship with two tables, Parent with many Child.
I create a parent and add children to it. Then I either create it (if it’s a new parent) or update it (if it exists already.) When I create it, everything works properly. However, if I update it, the children don’t update.
using (var Repo = new ParentRepository(context))
{
var key = new AnnualFormKey(prnt.Year, prnt.UserId);
if (Repo.Retrieve(key) == null)
{
prnt.CreatedDate = DateTime.Now;
prnt.CreatedId = 1;
Repo.Create(prnt);
Repo.SaveChanges(); //creates parent and children
}
else
{
prnt.UpdatedDate = DateTime.Now;
prnt.UpdatedId = 2;
Repo.Update(prnt);
Repo.SaveChanges(); //updates parent but not children
}
}
(Note: Update calls _context.Entry(orginal).CurrentValues.SetValues(entity)
Is this a problem with my context or do I need to do something else?
Okay, I looked this up more in depth and discovered that Entity Framework doesn’t actually update complex entities (as in, it won’t save the children). There are lots of complicated workarounds, but mine was very simple. I just deleted the existing entity and created it again (using the updated version).