为什么EF从数据库加载数据并忽略本地更改?

时间:2017-04-04 06:06:58

标签: c# entity-framework

我有以下代码:

        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中获取行,忽略了我刚才在前几行中所做的任何更改,为什么会这样,我该如何避免呢?

2 个答案:

答案 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)