【问题标题】:returning null value from populated selectlist with DB data使用数据库数据从填充的选择列表返回空值
【发布时间】:2020-02-19 12:41:08
【问题描述】:

我正在实施 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: 对象引用未设置为对象的实例。

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

【问题讨论】:

  • 能否请您从 dbcontext 添加您的OnModelCreating
  • _context.EntityType.Where(g=&gt;g.EntityKey=="sentResponseType").Include(x=&gt;x.ApiApplicantHistoryLastReqStatusNavigation).ToList() 或在您的模态创建创建protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) =&gt; optionsBuilder .UseLazyLoadingProxies() .UseSqlServer(myConnectionString); 了解更多信息docs.microsoft.com/en-us/ef/core/querying/related-data
  • 你没有在视图中使用你声明的 ViewModel
  • 感谢您的回复。您能否更清楚地解释您的答案?
  • 你可以在你的 create 方法中尝试var ent =_context.EntityType.Where(g=&gt;g.EntityKey=="sentResponseType") .Include(x=&gt;x.ApiApplicantHistoryLastReqStatusNavigation).ToList() 并检查它的响应吗?

标签: asp.net-core-mvc ef-core-2.0


【解决方案1】:

我希望您使用 EF 核心作为 ORM,因为您使用的是 Asp.net core

EF core中加载相关数据。

可以通过 2 种方式或 延迟加载

预加载

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

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

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

在您的核心 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

【讨论】:

    【解决方案2】:

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

    在我的创建方法中。

    我的问题在创建视图中,在下面的行中,apiApplicantHistoryvm 中存在一个空值:

    【讨论】:

      【解决方案3】:

      感谢您的帮助。问题出在我的代码中 ViewData["sentResponseType"] = new SelectList(_context.EntityType.Where(g => g.EntityKey == "sentResponseType").ToList(), "ID", "name");

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2016-12-08
        • 1970-01-01
        • 2015-04-04
        • 1970-01-01
        • 1970-01-01
        • 2010-09-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多