StackOverflower
StackOverflower

Reputation: 5761

How to update a detached object with a collection inside on EF 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?

Upvotes: 4

Views: 3156

Answers (2)

Grigor Aleksanyan
Grigor Aleksanyan

Reputation: 550

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))
        {
            _dbSet.Attach(entity);
        }
    }

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

Upvotes: 0

Sampath
Sampath

Reputation: 65870

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

Upvotes: 3

Related Questions