I have two Models called "Client" and "Software". Clients can have the same Software and Software can be on multiple clients. I want to add a List of Software to a specific Client.
Client Model:
public class Client
{
[Key]
public int id { get; set; }
[Required]
public ICollection<Software>? Softwares { get; set; }
}
Software Model:
public class Software
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int id { get; set; }
public ICollection<Client>? Clients { get; set; }
}
Why does this throw a 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
}
}
}
Repo Code
public Client getClientByID(int id)
{
return _context.Clients.Find(id);
}
repo.getClientByID(Convert.ToInt32(clientid));code