简体   繁体   English

ASP.NET 5 和 EF - 用 LINQ 替换子列表

[英]ASP.NET 5 and EF - Replace child list with LINQ

I am working on an API controller for an ASP.NET project, and I have ran into an issue.我正在为 ASP.NET 项目开发 API controller,我遇到了一个问题。 I have a Computer object with a one-to-many relationship with a Services object. When a Computer is added that has an IP identical to an existing Computer in the database, I want to replace the old Computer's attributes, as well as replace the associated Services collection.我有一台计算机 object 与服务 object 具有一对多关系。当添加一台计算机时,它的 IP 与数据库中的现有计算机相同,我想替换旧计算机的属性,以及替换关联的服务集合。 However, when I try to replace the Services collection, it adds onto the existing Services instead of replacing it.但是,当我尝试替换 Services 集合时,它会添加到现有 Services 而不是替换它。

Computer Model电脑 Model

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

Services Model服务 Model

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

Computer Controller电脑 Controller

[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
}

What changes should I make in order to replace the Services collection instead of adding onto it?为了替换 Services 集合而不是添加到它,我应该做哪些更改?

You need to load existing entities and then clear the collection and replace with the new ones.您需要加载现有实体,然后清除集合并替换为新实体。

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
}

If you can actually do an upsert and delete removed services, it might be more efficient in your case but that bit of model is not apparent to me.如果您实际上可以执行更新插入并删除已删除的服务,那么在您的情况下它可能会更有效,但 model 的那一点对我来说并不明显。

Maybe you could try to do a Clear() on the Services on the line prior to the one where you set the new one.也许您可以尝试在设置新服务之前在线上的服务上执行 Clear()。

oldComputer.Services.Clear(); oldComputer.Services.Clear();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM