Home > database >  Add list to object in Entity Framework
Add list to object in Entity Framework

Time:10-17

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);
        }

CodePudding user response:

Because you need to include Softwares when fetching from Clients table in database

In your repo, change your code to be like this :

public Client getClientByID(int id)
{
     return _context.Clients.Include(k => k.Softwares).First(i => i.id == id);
}

CodePudding user response:

Here, two objects can be null, both the client itself and the software list, But your error occurs because the list of software is null, to solve this problem you need to load the list of software when receiving Client information from the database,But before that, you must make sure of the existence of the Client. solve it as follows:

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);
}
  • Related