我正在為 ASP.NET 專案開發 API 控制器,但遇到了一個問題。我有一個與 Services 物件具有一對多關系的 Computer 物件。當添加的計算機具有與資料庫中現有計算機相同的 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
}
為了替換服務集合而不是添加到它上面,我應該進行哪些更改?
uj5u.com熱心網友回復:
您需要加載現有物體,然后清除集合并替換為新物體。
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 并洗掉已洗掉的服務,那么在您的情況下它可能更有效,但這種模型對我來說并不明顯。
uj5u.com熱心網友回復:
也許您可以嘗試在設定新服務之前在線上的服務上執行 Clear() 。
oldComputer.Services.Clear();
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/361684.html
