2017-04-04 72 views
1

我有以下代碼:EF爲什麼從數據庫加載數據並忽略本地更改?

 var existingParticipant = Context.CaseParticipants.Where(p => p.CaseId == caseId); 
     foreach (var cp in existingParticipant) 
     { 
      var ncp = caseParticipantList.First(a => a.Id == cp.Id); 
      cp.IsIncompetent = ncp.IsIncompetent; 
      cp.IsLeave = ncp.IsLeave; 
      cp.SubstituteUserId = ncp.IsPresent ? null : ncp.SubstituteUserId; 
     } 
     var withSubs = existingParticipant.Where(c => c.SubstituteUserId != null).ToList(); 

讓我吃驚的是,最後一行從數據庫獲取的行第二次,無視我剛纔在前面的線來完成的任何變化,這是什麼原因,我如何避免它?

回答

2

我覺得你的問題是,你的existingParticipant是一個查詢,而不是一個列表。該查詢得到執行foreach,但existingParticipant仍然保留查詢,將再次調用ToList()時將在數據庫上執行。爲了解決它,請立即執行初始查詢,並以這種方式在您更改的實體的內存中工作。

IList<...> existingParticipant = Context.CaseParticipants.Where(p => p.CaseId == caseId).ToList(); // Explicit executing of query 
foreach (var cp in existingParticipant) 
{ 
    var ncp = caseParticipantList.First(a => a.Id == cp.Id); 
    cp.IsIncompetent = ncp.IsIncompetent; 
    cp.IsLeave = ncp.IsLeave; 
    cp.SubstituteUserId = ncp.IsPresent ? null : ncp.SubstituteUserId; 
} 
var withSubs = existingParticipant.Where(c => c.SubstituteUserId != null).ToList(); // Working in memory on list 
1

類型existingParticipants的是IQueryable的,這意味着你不會得到對象到內存中,但只有一個查詢自身數據庫直接

如果希望在處理你的對象到內存中調用.ToList()工作

Context.CaseParticipants.Where(p => p.CaseId == caseId)

相關問題