实体框架如何正确更新实体代码?

ash*_*ina 4 c# entity-framework ef-code-first

我的通用存储库中有以下更新方法

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

所述UnitOfWork具有调用提交方法SaveChanges上下文.更多详细信息,请访问
https://codereview.stackexchange.com/questions/19037/entity-framework-generic-repository-pattern

当我更新实体然后调用

ProductRepository.Update(modifiedProduct);
UnitOfWork.Commit;
Run Code Online (Sandbox Code Playgroud)

什么都没有浮动到数据库.

但是,仅仅调用Commit工作(不调用更新方法).

那么,Attach方法的作用是什么导致更改不会流向数据库.我认为附加调用是在Update方法中进行的正确调用.那么,是什么导致了意外的行为.

来自CodePlex上的EF源代码

/// <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;
}
Run Code Online (Sandbox Code Playgroud)

dev*_*tal 5

///     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. 
Run Code Online (Sandbox Code Playgroud)

附加实体后,状态将为Unchanged,因此不会为该实体触发UPDATE sql.您需要在附加后手动设置实体的状态.