2012-07-06 32 views
1

問題兩個引用同一個域/實體模型

我要救當用戶編輯他們已經改變了模型的屬性。這是我想做的事情......

  1. 檢索編輯視圖模型
  2. 獲取域模型和映射回更新的價值
  3. 呼籲存儲庫的更新方法
  4. 獲取的「老字號」的域模型和比較
  5. 存儲字段的值更改的值(JSON)到表

但是我有步數的麻煩4.看來日在實體框架中不想再次訪問數據庫以獲取具有舊值的模型。它只是返回我擁有的實體。

嘗試的解決方案

我已經使用Find()SingleOrDefault()方法試過,但他們只是迴歸模型我現在有。

示例代碼

private string ArchiveChanges(T updatedEntity) 
{ 
    //Here is the problem! 
    //oldEntity is the same as updatedEntity 
    T oldEntity = DbSet.SingleOrDefault(x => x.ID == updatedEntity.ID); 

    Dictionary<string, object> changed = new Dictionary<string, object>(); 

    foreach (var propertyInfo in typeof(T).GetProperties()) 
    { 
     var property = typeof(T).GetProperty(propertyInfo.Name); 

     //Get the old value and the new value from the models 
     var newValue = property.GetValue(updatedEntity, null); 
     var oldValue = property.GetValue(oldEntity, null); 

     //Check to see if the values are equal 
     if (!object.Equals(newValue, oldValue)) 
     { 
      //Values have changed ... log it 
      changed.Add(propertyInfo.Name, newValue); 
     } 
    } 

    var ser = new System.Web.Script.Serialization.JavaScriptSerializer(); 
    return ser.Serialize(changed); 
} 

public override void Update(T entityToUpdate) 
{ 
    //Do something with this 
    string json = ArchiveChanges(entityToUpdate); 

    entityToUpdate.AuditInfo.Updated = DateTime.Now; 
    entityToUpdate.AuditInfo.UpdatedBy = Thread.CurrentPrincipal.Identity.Name; 

    base.Update(entityToUpdate); 
} 
+0

此代碼後,您已更新reporistory?多數民衆贊成在你的腳步,這聽起來像。如果是這樣,那麼你會得到新的模型;你更新了舊模型。如果你想這樣做,你需要在更新之前得到舊的模型。 – Tyrsius 2012-07-06 20:04:46

+0

@Tyrsius之前沒有。我添加了更清晰畫面的調用方法。 – 2012-07-06 20:07:09

+1

您正在處理/更新的實體附加到上下文(已跟蹤)。這意味着如果修改它,它將進入修改狀態(這意味着當調用SaveChanges時,它將執行數據庫中的更新)。但是,當僅查詢實體(SingleOrDefault調用)時,由於實體附加到上下文(在內存緩存中),它將直接從上下文中檢索,並且不會往返DB。如果您想從數據庫中檢索實體,則需要將實體從當前上下文中分離出來(然後重新連接,以便對SaveChanges的調用實際上會更新數據庫)。 – darkey 2012-07-06 20:39:54

回答

2

的問題是,實體框架緩存是它在DbSet讀取對象。所以當你第二次請求對象時,它不會進入數據庫,因爲它已經加載了它。

不過,好消息是實體自動跟蹤原始值。看到這個問題的信息如何讓他們:How to get original values of an entity in Entity Framework?

相關問題