簡體   English   中英

帶有UoW更新的EF存儲庫

[英]EF Repository with UoW Update

我相信這是在其他地方提出來的,但我找不到直接的解決方案。 我的Api正在傳遞對象模型,並且在服務器端,該未傳遞對象的每個值都被視為null(有意義)。 有沒有辦法我可以告訴EF6不要用傳遞的對象中的空值更新實體,而不必編寫每個屬性並檢查它是否為空。

偽代碼

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

我的問題是,具有空值的任何數據實際上都會重寫具有空值的現有數據庫記錄值。

請指出解決方案或文章。 我應該反思一下,也許自動映射器可以解決這個問題(我相信這不是它的目的),或者應該編寫某種輔助方法,因為我的對象可以包含子對象。

先感謝您。

你可以做這樣的事情

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

有些場景需要您更新對象的一部分,有時需要更新其他部分,我認為最好的方法是傳遞字段以將其排除在更新之外

希望對你有幫助

就個人而言,不喜歡在更新之前先打數據庫並執行get操作。 可能在進行ajax調用時,您可以發送應更新的屬性列表(以便也可以處理更新為null值(擦除現有值)的情況)。

我正在對@Hadi Hassan所做的事情做一些小修改(無需訪問數據庫即可獲取實體):

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(field).IsModified不適用於相關實體

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM