-2

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?

Ian Kemp
  • 28,293
  • 19
  • 112
  • 138
si2030
  • 3,895
  • 8
  • 38
  • 87
  • PLEASE ENABLE LAZY LOAD IN STARTUP.CS services.AddDbContext(options => { options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")).UseLazyLoadingProxies(); }); – Dharmeshsharma Feb 19 '20 at 12:21
  • same error i got in .net core with code first so i just enable lazy loading and refer to this microsoft url https://learn.microsoft.com/en-us/ef/core/querying/related-data – Dharmeshsharma Feb 19 '20 at 12:22
  • 3
    If `job.WarrantyCompany` can be `null`, then this has nothing to do with EF Core. Just use `WarrantyCompany = job.WarrantyCompany?.CompanyName` as in any nullable aware code. – Ivan Stoev Feb 19 '20 at 12:38
  • 1
    Does this answer your question? [What is a NullReferenceException, and how do I fix it?](https://stackoverflow.com/questions/4660142/what-is-a-nullreferenceexception-and-how-do-i-fix-it) – Ian Kemp Feb 19 '20 at 13:02

1 Answers1

0

PLEASE ENABLE LAZY LOAD IN STARTUP.CS for navigation

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

        });

refer to microsoft url "https://learn.microsoft.com/en-us/ef/core/querying/related-data"

Also add virtual in navigation property

 public virtual Client? WarrantyCompany { get; set; }
Dharmeshsharma
  • 683
  • 1
  • 11
  • 28
  • Thankyou for your answer.... however I have a slightly different line to the standard one above: services.AddDbContext(options => options.UseSqlServer(_configuration.GetConnectionString("CatalogConnection"), b => b.MigrationsAssembly("JobsLedger.CATALOG"))); How do I add lazy loading this? I tried it and its not accepting it anywhere? – si2030 Feb 19 '20 at 12:57