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)
{
// Update parent
_dbContext.Entry(existingParent).CurrentValues.SetValues(model);
// Delete children
foreach (var existingChild in existingParent.Children.ToList())
{
if (!model.Children.Any(c => c.Id == existingChild.Id))
_dbContext.Children.Remove(existingChild);
}
// Update and Insert children
foreach (var childModel in model.Children)
{
var existingChild = existingParent.Children
.Where(c => c.Id == childModel.Id)
.SingleOrDefault();
if (existingChild != null)
// Update child
_dbContext.Entry(existingChild).CurrentValues.SetValues(childModel);
else
{
// Insert child
var newChild = new Child
{
Data = childModel.Data,
//...
};
existingParent.Children.Add(newChild);
}
}
_dbContext.SaveChanges();
}
}
Also in C#:
- c# stop loop in method
- unity drawline
- string to uint c#
- c# asp.net hover tooltip
- unity delete all children
- findobject getcomponent
- convert string array to int C#
- json ignore property c#
- c# sort array
- rotatearound unity
- unity add sections to a list
- c# web form compare dates
- download and run exe c# 1 button
- list clone - C#
- devexpress objectspace to session
- unity face direction of movement
- unity make a int arry with preset values
- how to add movement in unity
- split string in c#
- set label position winforms
- c# wpf row definition height * in code
- .netstandard distinctby iqueryable
- c# new thread
- press key run code unity c#