Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Add list to object in Entity Framework

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

>Solution :

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);
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading