How to update a detached object with a collection inside on EF Core?

c# entity-framework entity-framework-core


I have a detached object which contains a collection. I'm attaching it using this code

EntityEntry dbEntityEntry = _context.Entry<T>(entity);
dbEntityEntry.State = EntityState.Modified;

Detached object saves perfectly if I change most of the fields.. the issue is with a collection this object has. Changes on the collection are not persisted. I've seen the query executed and it onl touches the "main" table. All dependent relations are not updated

Is there any way to update the entire tree for a detached object?

8/27/2016 4:13:26 AM

Accepted Answer

Problem :

EF is not aware of the changed collection or about the navigation properties.By setting the State of the dbEntityEntry to EntityState.Modified, EF only knows that the object dbEntityEntry has been changed. This means that EF will only update dbEntityEntry but not it's navigation properties.

Solution :

You can iterate over all collection (or navigation properties) of the current dbEntityEntry and set the entity state to EntityState.Modified.

Another Solution : Please see that too.May be helped to you.

Working with Self-Tracking Entities

8/27/2016 12:49:45 PM

Popular Answer

I can suggest the way that I found in some framework. Because there are many problems with entity updates, if you use ASP. Before update just call this method

 protected virtual void AttachIfNot(TEntity entity)
        if (!_dbSet.Local.Contains(entity))

For navigation properties, just do same way by iterating in collection.

Related Questions


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