我有一個客戶模型:
public class Client
{
[Key]
public int id { get; set; }
[Required]
public string? Hostname { get; set; }
public ICollection<Software>? Softwares { get; set; }
}
以及帶有軟體的模型:
public class Software
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int id { get; set; }
public string Name { get; set; }
public ICollection<Client>? Clients { get; set; }
}
這應該是一個 n 到 n 連接。如何向我的客戶添加軟體?
我試過的:
public async void add(Software software)
{
using (var repo = new ClientRepository(contextFactory.CreateDbContext()))
{
client.Softwares.Add(software);
await repo.Save(client);
}
存盤庫:
public async Task Save(Client client)
{
_context.Clients.Update(client);
_context.SaveChanges();
}
}
這適用于我添加的第一個軟體,但如果我嘗試添加第二個軟體,則會出現以下錯誤:
SqlException:違反主鍵約束“PK_ClientSoftware”。無法在物件“dbo.ClientSoftware”中插入重復鍵。重復鍵值為 (7003, 5002)。
uj5u.com熱心網友回復:
問:你每次都用 new() 做一個新的嗎?
A:不,它是一個已經存在的軟體
那么這就是錯誤。
第一個 SaveChanges() 將開始跟蹤它作為現有。您可以檢查:ID 將是!= 0。
當您稍后將其添加到同一個客戶端時,您將收到重復錯誤。
所以在你的代碼中的某個地方:
await add(software); // existing
software = new Software(); // add this
相關,變化:
public async void add(Software software)
至
public async Task Add(Software software)
始終避免async void。
uj5u.com熱心網友回復:
看來您要添加多個相同的關系。在向客戶端添加軟體之前,請確保關系不存在,然后您可以繼續向客戶端添加軟體。
此外,您可以改進您的物體。對主鍵使用更好的命名,并為類添加[Key]屬性。Software
Client:
public class Client
{
public Client()
{
Softwares = new HashSet<Software>();
}
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ClientId { get; set; }
[Required]
public string Hostname { get; set; }
public ICollection<Software> Softwares { get; set; }
}
Software:
public class Software
{
public Software()
{
Clients = new HashSet<Client>();
}
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int SoftwareId { get; set; }
public string Name { get; set; }
public ICollection<Client> Clients { get; set; }
}
檢查關系是否已經存在:
// Get the client including its related softwares
var client = dbContext.Clients.Include(x => x.Softwares)
.FirstOrDefault(x => x.Hostname == "Ibrahim");
if (client != null)
{
// Check with unique property such as name of software
// If it does not exist in this current client, then add software
if (!client.Softwares.Any(x => x.Name == software.Name))
client.Softwares.Add(software);
dbContext.SaveChanges();
}
注意:如果您更新物體,請記住創建新的遷移和資料庫。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/531575.html
上一篇:在Blazor服務器端應用程式中呼叫WEBAPI是一種好習慣嗎?
下一篇:C#控制器行為根據變數名改變
