Search
 
SCRIPT & CODE EXAMPLE
 

CSHARP

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();
    }
}
Comment

PREVIOUS NEXT
Code Example
Csharp :: print random number unity 
Csharp :: c# how to get connection string from app config 
Csharp :: how do I print something in the console at the start of the game unity 
Csharp :: memset alternative in c# 
Csharp :: function in Razor Pages 
Csharp :: how to create a list in c# unity 
Csharp :: get hard disk serial number 
Csharp :: list of string to string c# 
Csharp :: call stored proc c# 
Csharp :: Find an item in a list by LINQ 
Csharp :: c# datagridview filter textbox 
Csharp :: hashset to list c# 
Csharp :: add object to list c# 
Csharp :: default generic parameter for method in c# 
Csharp :: how to make a mouse down condition in C# 
Csharp :: c# add picturebox to form 
Csharp :: c# join string array 
Csharp :: c# convert split to list 
Csharp :: csharp sleep code 1 second 
Csharp :: unity c# log an error or warning 
Csharp :: c# list with 0 initialize 
Csharp :: unity key up 
Csharp :: function in c# to do addition 
Csharp :: add mime type for woff in web.config 
Csharp :: c# print list 
Csharp :: c# inline array initialization 
Csharp :: Unity Children Destroy 
Csharp :: what is type unity 
Csharp :: how to add a gameobject 
Csharp :: Operator Overloading | C# 
ADD CONTENT
Topic
Content
Source link
Name
9+5 =