使用数据库数据从填充的选择列表中返回空值

问题描述 投票:0回答:3

我正在实现asp.net核心MVC项目。在名为ApiApplicant的Create方法的控制器类中,我有3个选择列表,应从名为APIApplicantHistory的表中填充其项目。我的模型,创建方法和视图的实现如下:

    using System.Collections.Generic;

      namespace CSDDashboard.Models
     {
      public partial class Apiapplicant
      {
        public Apiapplicant()
        {
            ApiApplicantHistory = new HashSet<ApiApplicantHistory>();
        }

        public int Id { get; set; }
        public string ApiRequestDate { get; set; }
        public int? ApiRequestNo { get; set; }
        public int? Apiid { get; set; }
        public int? ApplicantId { get; set; }
        public int? GateId { get; set; }
        public string NocRequestDate { get; set; }
        public string NocRequestNo { get; set; }
        public string Url { get; set; }
        public string Description { get; set; }
        public bool? IsDeleted { get; set; }

        public virtual Api Api { get; set; }
        public virtual Applicant Applicant { get; set; }
        public virtual Gate Gate { get; set; }
        public virtual ICollection<ApiApplicantHistory> ApiApplicantHistory { get; set; }
    }
}

     using System;
     using System.Collections.Generic;

     namespace CSDDashboard.Models
     {
     public partial class ApiApplicantHistory
     {
        public int Id { get; set; }
        public int? ApiApplicantId { get; set; }
        public string Date { get; set; }
        public int? SentResponseType { get; set; }
        public int? UnconfirmedReason { get; set; }
        public int LastReqStatus { get; set; }
        public string Description { get; set; }

           public virtual Apiapplicant ApiApplicant { get; set; }
           public virtual EntityType LastReqStatusNavigation { get; set; }
           public virtual EntityType SentResponseTypeNavigation { get; set; }
           public virtual EntityType UnconfirmedReasonNavigation { get; set; }
        }
       }


       using System;
       using System.Collections.Generic;

       namespace CSDDashboard.Models
       {
        public partial class EntityType
       {
        public EntityType()
        {
            ApiApplicantHistoryLastReqStatusNavigation = new HashSet<ApiApplicantHistory>();
            ApiApplicantHistorySentResponseTypeNavigation = new HashSet<ApiApplicantHistory>();
            ApiApplicantHistoryUnconfirmedReasonNavigation = new HashSet<ApiApplicantHistory>();
        }

        public int Id { get; set; }
        public string Name { get; set; }
        public string EntityKey { get; set; }

        public virtual ICollection<ApiApplicantHistory> ApiApplicantHistoryLastReqStatusNavigation { get; set; }
        public virtual ICollection<ApiApplicantHistory> ApiApplicantHistorySentResponseTypeNavigation { get; set; }
        public virtual ICollection<ApiApplicantHistory> ApiApplicantHistoryUnconfirmedReasonNavigation { get; set; }

    }
}


      using System;
      using System.Collections.Generic;
      using System.Linq;
      using System.Threading.Tasks;

      namespace CSDDashboard.Models
      {
      public class APIApplicantViewModel
      {
            public Apiapplicant apiApplicantvm { get; set; }

             public ApiApplicantHistory apiApplicantHistoryvm { get; set; }
       }
      }


       public class ApiapplicantsController : Controller
       {
        private readonly CSSDDashboardContext _context;

        public ApiapplicantsController(CSSDDashboardContext context)
        {
            _context = context;
        }

       public IActionResult Create()
        {

            ViewData["sentResponseType"] = new SelectList(_context.EntityType.Where(g => g.EntityKey == "sentResponseType").ToList(), "ID", "name");
            ViewData["unconfirmedReason"] = new SelectList(_context.EntityType.Where(g => g.EntityKey == "unconfirmedReason").ToList(), "ID", "name");
            ViewData["lastReqStatus"] = new SelectList(_context.EntityType.Where(g => g.EntityKey == "lastRequestStatus").ToList(), "ID", "name");

            return View();

        }
       }

以及创建视图实现的一部分:

     @model CSDDashboard.Models.APIApplicantViewModel

       @{
       ViewData["Title"] = "create";
       }
        <div class="row">
         <div class="col-md-4">
          <form asp-action="Create">
            <div asp-validation-summary="ModelOnly" class="text-danger"></div>
          <div class="form-group">
                <label asp-for="apiApplicantvm.GateId" class="control-label"></label>
                <select asp-for="apiApplicantvm.GateId" class="form-control" asp-items="ViewBag.GateId"></select>
            </div>
        <div class="form-group">
    <label asp-for="apiApplicantHistoryvm.SentResponseType" class="control-label"></label>
        <select asp-for="apiApplicantHistoryvm.SentResponseType" class="form-control" asp-items="ViewBag.sentResponseType"></select>
        </div>
       <div class="form-group">
        <label asp-for="apiApplicantHistoryvm.UnconfirmedReason" class="control-label"></label>
        <select asp-for="apiApplicantHistoryvm.UnconfirmedReason" class="form-control" asp-items="ViewBag.unconfirmedReason"></select>

       </div>
        <div class="form-group">
            <label asp-for="apiApplicantHistoryvm.LastReqStatus" class="control-label"></label>
            <select asp-for="apiApplicantHistoryvm.LastReqStatus" class="form-control" asp-items="ViewBag.lastReqStatus"></select>
        </div>
<div class="form-group">
                    <input type="submit" value="Create" class="btn btn-primary" />
                </div>
        </form>
       </div>
      </div>

       <div>
       <a asp-action="Index">Back</a>
       </div>

     @section Scripts {
      @{await Html.RenderPartialAsync("_ValidationScriptsPartial");}
    }

在create方法中,所有viewData均填充有正确的相关数据,但Create视图中存在问题,运行项目后,在Create页面中显示如下错误:

[处理请求时发生未处理的异常。NullReferenceException:对象引用未设置为对象的实例。

调试代码后,我了解到在create视图中,apiApplicantvm不为null,但apiApplicantHistoryvm返回null,因此出现上述错误。如果有人可以告诉我如何解决此问题,我将不胜感激。

asp.net-core-mvc ef-core-2.0
3个回答
0
投票

我希望您将EF内核用作ORM,因为您正在使用Asp.net core

要在EF core中加载相关数据。

可以通过两种方式完成,或者延迟加载

急切加载

_context.EntityType.Where(g=>g.EntityKey=="sentResponseType") .Include(x=>x.ApiApplicantHistoryLastReqStatusNavigation).ToList()

OR

延迟加载在您的模态创建中

protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) => optionsBuilder .UseLazyLoadingProxies() .UseSqlServer(myConnectionString);

OR

在您的核心MVC项目的startup.cs中延迟加载示例。

.AddDbContext<BloggingContext>( b => b.UseLazyLoadingProxies() .UseSqlServer(myConnectionString));

有关更多信息docs.microsoft.com/en-us/ef/core/querying/related-data

https://docs.microsoft.com/en-us/ef/core/querying/related-data


0
投票

非常感谢您的回答。我正在使用EF core,并且按照您的建议更改了代码。我添加了ViewData [“ sentResponseType”] =新的SelectList(_context.EntityType.Where(g => g.EntityKey ==“ sentResponseType”).Include(x => x.ApiApplicantHistoryLastReqStatusNavigation).ToList(),“ ID”,“ name”);

在我的创建方法中。

而且我的问题在此处的创建视图中,在以下行中,apiApplicantHistoryvm中存在空值:


0
投票

谢谢您的帮助。问题在我的代码中ViewData [“ sentResponseType”] =新的SelectList(_context.EntityType.Where(g => g.EntityKey ==“ sentResponseType”)。ToList(),“ ID”,“名称”);

根据我的EntityType模型,我应该使用ID而不是ID。

© www.soinside.com 2019 - 2024. All rights reserved.