gpt4 book ai didi

c# - 为什么EF会从数据库加载数据而忽略本地变化?

转载 作者:太空宇宙 更新时间:2023-11-03 23:00:43 25 4
gpt4 key购买 nike

我有以下代码:

        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();

让我感到惊讶的是,最后一行第二次从数据库中获取行,忽略了我刚刚在前面几行中所做的任何更改,这是为什么,我该如何避免呢?

最佳答案

我认为你的问题是你的 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

关于c# - 为什么EF会从数据库加载数据而忽略本地变化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43199460/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com