Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework How to properly Update an entity Code First?

I have the following update method in my generic 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);
    }
}

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

When I update an entity and then call

ProductRepository.Update(modifiedProduct);
UnitOfWork.Commit;

Nothing floats down to the database.

However , Merely calling the Commit works ( no call to the update method ).

So, what is the Attach Method doing that causes the changes to not flow down to the database. I think the attach call is the correct call to make in the Update Method. So, what is causing the unexpected behavior.

From the EF Source code on 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;
}
like image 716
ashutosh raina Avatar asked Jan 15 '23 17:01

ashutosh raina


1 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 attaching the entity, the state will be Unchanged, so no UPDATE sql is going to fire for that entity. You would need to manually set the state of the entity after attaching.

like image 174
devdigital Avatar answered Jan 31 '23 00:01

devdigital