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

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

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

最佳答案

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

相关文章:

c# - 用户 'NT AUTHORITY\SYSTEM' 登录失败。原因 : Failed to open the explicitly specified database

c# - Unity的 "register-by-convention"可以解析为抽象类吗?

c# - 这个错误是什么意思 : stale element reference: element is not attached to the page document?

c# - 带有 XML 文件的 Entity Framework

C# Entity Framework : How do I update a record and change foreign key reference?

c# - 如何从文件夹在 StackPanel WPF 中添加多个图像?

c# - SignalR:加载集线器时出错。 404 未找到

c# - C# Entity-Framework 中对象模型的过滤数据

c# - 简单的 MVC 评论审核

c# - 刷新 DB First EDMX 时如何保留 StoreGeneratedPattern 设置?