我在通用存儲庫下面的更新方法實體框架如何正確更新一個實體代碼?
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;
沒有飄下來到數據庫。
但是,僅僅調用提交工程(沒有調用更新方法)。
那麼,Attach Method是什麼導致更改不會流到數據庫。 我認爲附加調用是在更新方法中進行的正確調用。那麼,是什麼導致了意外的行爲。
從EF的源代碼在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;
}
所以我需要將EntityState設置爲修改..但我的問題是,目前我的倉庫對上下文一無所知。無論如何圍繞它? –
我認爲在存儲庫級別更好。如果沒有,您不使用(隱藏)EF的某些功能。 –
是的,您的存儲庫應該具有對上下文的引用,如果您希望跨存儲庫共享上下文,則它可以是依賴項。 – devdigital