【问题标题】:ASP.NET 5 and EF - Replace child list with LINQASP.NET 5 和 EF - 用 LINQ 替换子列表
【发布时间】:2021-12-30 18:48:59
【问题描述】:

我正在为 ASP.NET 项目开发 API 控制器,但遇到了问题。我有一个与服务对象具有一对多关系的计算机对象。添加与数据库中现有计算机具有相同 IP 的计算机时,我想替换旧计算机的属性,以及替换关联的服务集合。但是,当我尝试替换 Services 集合时,它会添加到现有的 Services 中而不是替换它。

计算机模型

public class Computer
{
    public int ComputerId { get; set; }
    public string Ip { get; set; }
    public string Os { get; set; }
    public IList<Service> Services { get; set; }
        
}

服务模型

public class Service
{
    public int ServiceId { get; set; }
    public int ComputerId { get; set; }
    public int Port {get; set;}
    public int Version {get; set;}
}

计算机控制器

[HttpPost]
...
Computer oldComputer = _context.Computers.FirstOrDefault(y => y.Ip == newComputer.Ip);
if(oldComputer != null) {
   oldComputer.Hostname = newComputer.Hostname;
   oldComputer.Os = newComputer.Os;
   oldComputer.Services = newComputer.Services?.ToList(); //this adds new services to old services collection instead of replacing it
}

为了替换 Services 集合而不是添加到它,我应该进行哪些更改?

【问题讨论】:

    标签: c# asp.net entity-framework asp.net-core


    【解决方案1】:

    您需要加载现有实体,然后清除集合并替换为新实体。

    Computer oldComputer = _context.Computers.Include(c => c.Service).FirstOrDefault(y => y.Ip == newComputer.Ip);
    if(oldComputer != null) {
       oldComputer.Hostname = newComputer.Hostname;
       oldComputer.Os = newComputer.Os;
       oldComputer.Services.Clear();
       oldComputer.Services = newComputer.Services?.ToList(); //this adds new services to old services collection instead of replacing it
    }
    

    如果您实际上可以执行 upsert 并删除已删除的服务,那么在您的情况下它可能会更有效,但这种模型对我来说并不明显。

    【讨论】:

    • 你提到的第二种方法我该怎么做?我更新了服务模型。顺便说一句,你的回答很好。
    • 另外,它似乎适用于第一个 Post 请求,但连续的 post 请求会像以前一样添加到服务中。
    • 这有点复杂。您需要有身份,检查身份何时匹配以更新现有对象,当传入 id 为 0 或您从客户端发送的任何哨兵值时添加,并删除任何在传入列表中未找到的 id。
    • 有些东西可能会保留您的上下文。将其范围限制为每个请求。
    • 对不起,如果这是一个明显的问题,但是否有一个链接解释了如何限制每个请求的范围?
    猜你喜欢
    • 1970-01-01
    • 2021-07-22
    • 2021-10-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-07
    • 1970-01-01
    • 2016-08-10
    • 1970-01-01
    相关资源
    最近更新 更多