Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR CSHARP

Entity framwork update parent entity added new sub entity

//Interests
//Delete children
foreach (var existingChild in dbProfile.Interests.ToList())
{
    if (!profile.Interests.Any(c => c.Name == existingChild.Name))
        db.Interests.Remove(existingChild);
}

//Update and Insert children
foreach (var childModel in profile.Interests)
{
    var existingChild = dbProfile.Interests
        .Where(c => c.Name == childModel.Name)
        .SingleOrDefault();

    if (existingChild != null)
    {
        // Update child
        childModel.Id = existingChild.Id;
        db.Entry(existingChild).CurrentValues.SetValues(childModel);
    }
    else
    {
        // Insert child
        var newChild = new Interest
        {
            Name = childModel.Name,
        };
        dbProfile.Interests.Add(newChild);
    }
}
Source by entityframeworkcore.com #
 
PREVIOUS NEXT
Tagged: #Entity #framwork #update #parent #entity #added #entity
ADD COMMENT
Topic
Name
1+3 =