我在通用仓库中有以下更新方法
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
有一个提交方法,该方法调用上下文中的SaveChanges
。更多详细信息请参见此处:
https://codereview.stackexchange.com/questions/19037/entity-framework-generic-repository-pattern
当我更新一个实体并调用时:
ProductRepository.Update(modifiedProduct);
UnitOfWork.Commit;
没有任何东西会流向数据库。
然而,仅仅调用Commit就可以工作(不需要调用update方法)。
那么,Attach方法到底在做什么,导致更改无法流向数据库呢?我认为在Update方法中调用Attach方法是正确的。那么是什么导致了意外的行为呢?
从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;
}