2012-12-19 227 views
4

我在通用存儲庫下面的更新方法實體框架如何正確更新一個實體代碼?

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; 
} 

回答

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. 

連接實體後,國家將保持不變,因此沒有更新SQL是要觸發該實體。連接後您需要手動設置實體的狀態。

+0

所以我需要將EntityState設置爲修改..但我的問題是,目前我的倉庫對上下文一無所知。無論如何圍繞它? –

+0

我認爲在存儲庫級別更好。如果沒有,您不使用(隱藏)EF的某些功能。 –

+0

是的,您的存儲庫應該具有對上下文的引用,如果您希望跨存儲庫共享上下文,則它可以是依賴項。 – devdigital

4

您需要將對象附加爲modifiedadded以生成對數據庫的查詢。

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

public virtual T AttachAsModified(T item){db.Entry(item).State = System.Data。 EntityState.Modified}的作品...但是,添加_dbset.Attach(項目)導致問題支撐..我有沒有理解Attach方法不正確? –

+0

我們需要在連接實體後設置狀態。 –

+0

啊是啊:) –