entity framework update child collection code example
Example: entity framework update child records
public void Update(UpdateParentModel model)
{
var existingParent = _dbContext.Parents
.Where(p => p.Id == model.Id)
.Include(p => p.Children)
.SingleOrDefault();
if (existingParent != null)
{
_dbContext.Entry(existingParent).CurrentValues.SetValues(model);
foreach (var existingChild in existingParent.Children.ToList())
{
if (!model.Children.Any(c => c.Id == existingChild.Id))
_dbContext.Children.Remove(existingChild);
}
foreach (var childModel in model.Children)
{
var existingChild = existingParent.Children
.Where(c => c.Id == childModel.Id)
.SingleOrDefault();
if (existingChild != null)
_dbContext.Entry(existingChild).CurrentValues.SetValues(childModel);
else
{
var newChild = new Child
{
Data = childModel.Data,
};
existingParent.Children.Add(newChild);
}
}
_dbContext.SaveChanges();
}
}