我有兩個模型,稱為“客戶端”和“軟體”。客戶端可以擁有相同的軟體,并且軟體可以在多個客戶端上。我想將軟體串列添加到特定客戶端。
客戶型號:
public class Client
{
[Key]
public int id { get; set; }
[Required]
public ICollection<Software>? Softwares { get; set; }
}
軟體型號:
public class Software
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int id { get; set; }
public ICollection<Client>? Clients { get; set; }
}
為什么這會引發 NullReferenceException?
public void submit()
{
using (var repo = new ClientRepository(contextFactory.CreateDbContext()))
{
client = repo.getClientByID(Convert.ToInt32(clientid));
foreach (var software in toAddList)
{
client.Softwares.Add(software); //Error occurs here
}
}
}
回購代碼
public Client getClientByID(int id)
{
return _context.Clients.Find(id);
}
uj5u.com熱心網友回復:
Softwares因為從資料庫中的 Clients 表中獲取時需要包含
在您的倉庫中,將您的代碼更改為:
public Client getClientByID(int id)
{
return _context.Clients.Include(k => k.Softwares).First(i => i.id == id);
}
uj5u.com熱心網友回復:
這里,兩個物件可以是null,client本身和software串列,但是你的錯誤是因為串列software是null,要解決這個問題你需要在從資料庫 software接收Client資訊時加載串列,但在此之前,你必須確保的存在Client。解決如下:
public Client getClientByID(int id)
{
return _context.Clients.Include(s=>s.Softwares).FirstOrDefault(u => u.id == id);
}
client = repo.getClientByID(Convert.ToInt32(clientid));
if(client is null)
{
//Do somthing Like Return or throw new Exception
}
foreach (var software in toAddList)
{
client.Softwares.Add(software);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/515584.html
