Entity Framework How to update Code First entity correctly?

I have the following update method in my shared repository

public class Repository<T> : IRepository<T> where T : class { private readonly DbSet<T> _dbSet; public virtual T Update(T item) { return _dbSet.Attach(item); } } 

UnitOfWork has a commit method that calls SaveChanges in context. More here
https://codereview.stackexchange.com/questions/19037/entity-framework-generic-repository-pattern

When I update an object and then call

 ProductRepository.Update(modifiedProduct); UnitOfWork.Commit; 

Nothing floats in the database.

However, just calling Commit operations (no update method call).

So, what does the Attach method do, which leads to the fact that the changes will not go into the database. I think the attach call is the right call to make in the update method. So what causes unexpected behavior.

From EF source code to CodePlex

 /// <summary> /// Attaches the given entity to the context underlying the set. That is, the entity is placed /// into the context in the Unchanged state, just as if it had been read from the database. /// </summary> /// <param name="entity"> The entity to attach. </param> /// <returns> The entity. </returns> /// <remarks> /// Attach is used to repopulate a context with an entity that is known to already exist in the database. /// SaveChanges will therefore not attempt to insert an attached entity into the database because /// it is assumed to already be there. /// Note that entities that are already in the context in some other state will have their state set /// to Unchanged. Attach is a no-op if the entity is already in the context in the Unchanged state. /// </remarks> public object Attach(object entity) { Check.NotNull(entity, "entity"); InternalSet.Attach(entity); return entity; } 
+4
source share
2 answers
 /// Attach is used to repopulate a context with an entity that is known to already exist in the database. /// SaveChanges will therefore not attempt to insert an attached entity into the database because /// it is assumed to already be there. /// Note that entities that are already in the context in some other state will have their state set /// to Unchanged. 

After the object is attached, the state will be unchanged, so UPDATE sql will not start for this object. You will need to manually set the state of the object after joining.

+5
source

You need to attach the object as modified or added to create a query to the database.

  public virtual T AttachAsModified(T item) { item = _dbSet.Attach(item); db.Entry(item).State = System.Data.EntityState.Modified return item; } 
+4
source

All Articles