0

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);
        }
1
  • add repo.getClientByID(Convert.ToInt32(clientid)); code Commented Oct 17, 2022 at 7:27

2 Answers 2

2

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).Single(i => i.id == id);
}
Sign up to request clarification or add additional context in comments.

2 Comments

@HenkHolterman, For me since it is already an Id I would just use First(), because I am confident that there is only data anyway by the virtue of database constrain itself, no need for database to scan throught entire table to check for any possible duplicate during this data retrieval.
Alright, I will edit my code
1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.