【发布时间】: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