本文介绍了dotnet core 3 - 获取 System.NullReferenceException 可能是因为我没有加载正确的相关实体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我收到以下错误:

System.NullReferenceException: '未将对象引用设置为一个对象的实例.'

我是通过以下方法获得的:

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

特别是在这一部分:

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

问题在于:

        WarrantyCompany = job.WarrantyCompany.CompanyName,

问题是作业中的 WarrantyCompany 设置为允许空值.这是作业实体,您会注意到它有warrantyCompany 设置为允许空值:

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

具体来说,

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

所以 Job 有 WarrantyCompany 能够取空值......而且在很多情况下都是如此.我也放置作业的 ViewModel 如下:

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

你会注意到这个视图模型中的 WarrantyCompany 也可以取空值...

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

    public string? WarrantyCompany { get; set; }

当工作不是保修工作时,warrantyId 和warrantyCompany - 一个客户 - 为空:

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

错误显示如下:

那么我怎样才能让它设置一个空值而不抛出上述错误?

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

推荐答案

PLEASE ENABLE LAZY LOAD IN STARTUP.CS for navigation

PLEASE ENABLE LAZY LOAD IN STARTUP.CS for navigation

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

        });

参考微软网址 "https://docs.microsoft.com/en-us/ef/core/querying/related-data"

也在导航属性中添加虚拟

Also add virtual in navigation property

 public virtual Client? WarrantyCompany { get; set; }

这篇关于dotnet core 3 - 获取 System.NullReferenceException 可能是因为我没有加载正确的相关实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-12 07:27