Entity Framework will only save navigation properties for new entities, not updates

c# entity-framework entity-framework-6 navigation-properties

Popular Answer

The AddOrUpdate Method

You should seed your database using this technique. Which makes me believe you'll encounter some undesirable behaviours.

Let's start by fixing the manner in which you are changing the context.

public void Edit(Entity entity)
{
    var db = context
        .Include(i => i.Subset1)
        .Where(i => i.ID == id)
        .Single();

    // update entity
    context.Entry(db).CurrentValues.SetValues(entity);

    // delete / clear subset1 from database
    foreach (var dbSubset1 in db.Subset1.ToList())
    {
        if (!entity.Subset1.Any(i => i.ID == dbSubset1.ID))
            context.Subset1.Remove(dbSubset1);
    }

    foreach (var newSubset1 in entity.Subset1)
    {
        var dbSubset1 = db.Subset1.SingleOrDefault(i => i.ID == newSubset1.Id);
        if (dbSubset1 != null)
            // update Subset1
            context.Entry(dbSubset1).CurrentValues.SetValues(newSubset1);
        else
            db.Subset1.Add(newSubset1);
    }

    // save
    db.SaveChanges();
}

Making a method specifically to deal with the navigation property in the Microsoft Docs here is a fantastic approach to accomplish this in a much cleaner manner; locate the example approximately 3/4 of the way down the page.

Here is another quotation from the documents.

For most relationships, this can be done by updating either foreign key fields or navigation properties. For many-to-many relationships, the Entity Framework doesn't expose the join table directly, so you add and remove entities to and from the appropriate navigation properties.

1
8/4/2017 7:03:56 PM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow