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

C# 为什么EF从数据库加载数据而忽略本地更改?,c#,entity-framework,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.IsI

我有以下代码:

        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中获取行,忽略了我在前面几行中所做的任何更改,这是为什么,我如何避免

现有参与者的类型是IQueryable,这意味着您不会将对象放入内存,而只会直接在数据库上运行查询本身

如果要将对象处理到内存中,请在


Context.casepartments.Where(p=>p.CaseId==CaseId)

我认为您的问题在于您的
现有参与者
是一个查询,而不是一个列表。对于
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
IList existingParticipant=Context.caseAmpicipants.Where(p=>p.CaseId==CaseId.ToList();//查询的显式执行
foreach(现有参与者中的var cp)
{
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 with subs=existingParticipant.Where(c=>c.SubstituteUserId!=null).ToList();//在列表中的内存中工作