2016-08-29 37 views
2

我相信這是問別人,但我找不到直接的解決方案。 我的Api正在傳遞對象模型,並且在服務器端,那個未傳遞的對象的每個值都被認爲是null(有意義)。 有沒有辦法告訴EF6不要以傳遞對象的空值更新實體,我不需要寫每個屬性並檢查它是否爲空。EF倉庫與UoW更新

僞代碼

API

Update(int id, TaskEntity obj) 
{ 
    unitOfWork.Tasks.Update(id, userTask); 
    ... 
    unitOfWork.Save() 
} 

回購更新

Update(int id, T entity) 
     { 
      var existingRecord = Get(id); //Gets entity from db based on passed id 
      if (existingRecord != null) 
      { 
       var attachedEntry = Context.Entry(existingRecord); 
       attachedEntry.CurrentValues.SetValues(entity); 
      } 
     } 

我的問題是,隨着空值的任何數據實際上將改寫用null現有的數據庫記錄值。

請給我一個解決方案或文章,這是解決。我應該去思考,也許automapper可以處理這個(它不是我相信的目的),或者應該寫一些輔助方法,因爲我的對象可以包含子對象。

預先感謝您。

+0

您是否有TaskEntity中的屬性列表,您將在此更新方法中進行更新?或者你想更新所有的屬性,不是null。但是,那麼如何區分未提供的值與我想要刪除/更新爲空的值? – Developer

+0

如果我正確理解你的問題,你可以將所有相關信息傳遞給方法,並對整個實體進行更新。 – Eldho

+0

如果你想使用反射,你可以這樣做http://stackoverflow.com/questions/17385472/entity-framework-only-update-values-that-are-not-null。但個人我不覺得這是最好的東西 – Eldho

回答

5

你可以做這樣的事情

Update(int id, T entity,string[] excludedFields) 
{ 
    var existingRecord = Get(id); //Gets entity from db based on passed id 
    if (existingRecord != null) 
    { 
      var attachedEntry = Context.Entry(existingRecord); 
      attachedEntry.CurrentValues.SetValues(entity); 
      for(var field in excludedFields) 
      { 
       attachedEntry.Property(field).IsModified = false; 
      } 
    } 
} 

一些scenaries要求更新對象的一部分,有時其他部分,在我看來,最好的辦法是通過字段從更新中排除

希望它會幫助你

+0

我已經看到了某種解決方案,我可能會以某種布爾值結束,這將確定應該通過空值被忽略或更新,謝謝回答 – Raimonds

1

個人不打數據庫,並做更新之前做一個GET操作的大風扇。可能在執行ajax調用時,您可以發送一個您應該更新的屬性列表(以便更新爲空值(擦除現有值的場景)也將被處理)。

我做小的修改到什麼@Hadi哈桑做(沒有擊中用於獲取實體數據庫):

Update(T entity,string[] includedFields) 
{ 
    var existingRecord = Context.Attach(entity); // assuming primary key (id) will be there in this entity 
    var attachedEntry = Context.Entry(existingRecord); 

    for(var field in includedFields) 
    { 
     attachedEntry.Property(field).IsModified = true; 
    } 

} 

注 - attachedEntry.Property(場).IsModified不會爲相關工作實體