2017-04-04 2 views
1

私は、次のコードを持っている:私を驚かせたということである、なぜ最後の行は、私はちょうど前の行で行われた変更を無視して、DBから二度目の行をフェッチしていることは何ですか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のタイプは後に)あなたは、メモリ呼び出し.ToList(にあなたのオブジェクトを処理する場合は、メモリ内にオブジェクトを取得することはありませんが、唯一のクエリ自体が直接

データベースに取り組んつまり、のIQueryableです

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

関連する問題