Home » c# » c# – dotnet core 3 – Getting System.NullReferenceException maybe because I have not loaded the correct related entities-Exceptionshub

c# – dotnet core 3 – Getting System.NullReferenceException maybe because I have not loaded the correct related entities-Exceptionshub

Posted by: admin February 24, 2020 Leave a comment

Questions:

I am getting the following error:

System.NullReferenceException: ‘Object reference not set to an
instance of an object.’

I am getting it on the following method:

    private ClientIndexViewModel MapClientToVm(Client client) {
        ClientDATARepository.RelatedSuburbEntities(client.Suburb); // Bring all the related entities for "Suburb" down.

        var model = new ClientIndexViewModel {
            Id = client.Id,
            ClientNo = client.ClientNo,
            Company = client.Company,
            IsWarrantyCompany = client.IsWarrantyCompany,
            ClientFirstName = client.ClientFirstName,
            ClientLastName = client.ClientLastName,
            CompanyName = client.CompanyName,
            MobilePhone = client.MobilePhone,
            Active = client.Active,
            DeActivated = client.DateDeActivated != null
                ? client.DateDeActivated.Value.ToString("dd/MM/yyyy", CultureInfo.CurrentCulture)
                : "n/a",
            Activity = client.Activity,
            Address = new AddressViewModel {
                Address1 = client.Address1,
                Address2 = client.Address2,
                Suburb = new SuburbViewModel {
                    SuburbName = client.Suburb.SuburbName,
                    PostCode = client.Suburb.PostCode,
                    State = new StateViewModel {
                        Id = client.Suburb.State.Id,
                        StateName = client.Suburb.State.StateName,
                        StateShortName = client.Suburb.State.StateShortName
                    }
                }
            },
            NumberOfJobs = client.Jobs.Count.ToString(CultureInfo.CurrentCulture)
        };

        // Obtain any jobs the client has including any visits for those jobs.
        if (client.Jobs.Count > 0) {
            JobDATARepository
                .RelatedJobEntities(client.Jobs); // Bring all the related entities for "Jobs" collection down.

            foreach (var job in client.Jobs) {
                var jobViewModel = new ClientJobListingViewModel {
                    Id = job.Id,
                    AgentJobNo = job.AgentJobNo,
                    JobNo = job.JobNo,
                    Type = job.Type.Name,
                    Status = job.Status.StatusName,
                    WarrantyCompany = job.WarrantyCompany.CompanyName,
                    NumberOfVisits = job.Visits.Count.ToString(CultureInfo.CurrentCulture)
                };

                if (job.Visits.Count > 0)
                    foreach (var visit in job.Visits) {
                        var visitModel = new VisitViewModel {
                            Id = visit.Id,
                            VisitDate = visit.VisitDate.ToString("dd/MM/yyyy", CultureInfo.CurrentCulture),
                            StartTime = visit.StartTime.ToString("hh:mm", CultureInfo.CurrentCulture),
                            EndTime = visit.EndTime.ToString("hh:mm", CultureInfo.CurrentCulture)
                        };
                        jobViewModel.Visits.Add(visitModel);
                    }

                model.Jobs.Add(jobViewModel);
            }
        }

        return model;
    }

and specifically on this section:

foreach (var job in client.Jobs) 
{
    var jobViewModel = new ClientJobListingViewModel {
        Id = job.Id,
        AgentJobNo = job.AgentJobNo,
        JobNo = job.JobNo,
        Type = job.Type.Name,
        Status = job.Status.StatusName,
        WarrantyCompany = job.WarrantyCompany.CompanyName,
        NumberOfVisits = job.Visits.Count.ToString(CultureInfo.CurrentCulture)
};

The issue is with:

        WarrantyCompany = job.WarrantyCompany.CompanyName,

The thing is that WarrantyCompany in jobs is set to allow nulls. Here is the job entity and you will note that it has warrantyCompany set to allow nulls:

public class Job : IEntityBase, IAuditedEntityBase
    {
        public Job()
        {
            Visits = new List<Visit>();
        }

        public string? JobNo { get; set; }
        public string? AgentJobNo { get; set; }


        public int ClientId { get; set; } = default!;
        public Client Client { get; set; } = default!;

        public int? BrandId { get; set; }
        public Brand? Brand { get; set; }

        public int? TypeId { get; set; }
        public JobType? Type { get; set; }

        public int? StatusId { get; set; }
        public Status? Status { get; set; }

        public int? WarrantyCompanyId { get; set; }
        public Client? WarrantyCompany { get; set; }

        public string? Model { get; set; }
        public string? Serial { get; set; }
        public string? ProblemDetails { get; set; }
        public string? SolutionDetails { get; set; }
        public string? Notes { get; set; }

        public virtual ICollection<Visit> Visits { get; }

        public int Id { get; set; }
    }
#nullable disable

Specifically,

        public int? WarrantyCompanyId { get; set; }
        public Client? WarrantyCompany { get; set; }

So Job has WarrantyCompany able to take nulls… and it does in a lot of cases. The ViewModel that I am putting the jobs too is as follows:

public class ClientJobListingViewModel {
    public ClientJobListingViewModel() {
        Visits = new List<VisitViewModel>();
    }

    public int Id { get; set; }
    public string JobNo { get; set; }
    public string? AgentJobNo { get; set; }
    public string Type { get; set; }
    public string Status { get; set; }
    public string? WarrantyCompany { get; set; }
    public string NumberOfVisits { get; set; }

    public ICollection<VisitViewModel> Visits { get; }
}

and you will note that the WarrantyCompany in this view model can also take nulls…

    public string? WarrantyCompany { get; set; }

When the job is not a warranty job the warrantyId and warrantyCompany – a client – is null:

enter image description here

The error displays like this:

enter image description here

So how can I get it to set a null to this without throwing the above error?

How to&Answers:

PLEASE ENABLE LAZY LOAD IN STARTUP.CS for navigation

 services.AddDbContext<AppDbObjectContext>(options =>
        {
            options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")).UseLazyLoadingProxies();

        });

refer to microsoft url “https://docs.microsoft.com/en-us/ef/core/querying/related-data”

Also add virtual in navigation property

 public virtual Client? WarrantyCompany { get; set; }