我有以下代码:
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();
让我感到惊讶的是,最后一行是第二次从DB中获取行,忽略了我刚才在前几行中所做的任何更改,为什么会这样,我该如何避免呢?
答案 0 :(得分: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 :(得分:1)
现有参与者的类型是IQueryable,这意味着您不会将对象放入内存但只有查询本身直接处理数据库
如果要将对象处理到内存中,请在
之后调用.ToList()Context.CaseParticipants.Where(p =&gt; p.CaseId == caseId)