ASP.NET 5 和 EF - 用 LINQ 替换子列表
ASP.NET 5 and EF - Replace child list with LINQ
我正在为一个 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
}
我应该进行哪些更改才能替换服务集合而不是添加它?
您需要加载现有实体,然后清除集合并替换为新实体。
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
}
如果您真的可以执行更新插入和删除已删除的服务,那么在您的情况下它可能会更有效率,但我不太清楚这种模型。
我正在为一个 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
}
我应该进行哪些更改才能替换服务集合而不是添加它?
您需要加载现有实体,然后清除集合并替换为新实体。
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
}
如果您真的可以执行更新插入和删除已删除的服务,那么在您的情况下它可能会更有效率,但我不太清楚这种模型。