首页 > 解决方案 > 对象引用未设置为对象的实例。模型为空

问题描述

我正在尝试显示一个清单,该清单从 MySQL 数据库中获取数据并将其显示在视图中,并通过我们是否检查了设施来更新表中每个元素的变量 (IsChecked) 的值(我正在显示一些设施)。视图的模型是 Hotel_5.ViewModel.BookingRoom,其中 BookingRoom 是我使用多个模型创建的自定义模型。我在 Model.AmenitiesList.Count() 遇到了异常。模型为空。

这是我的看法

<div class="form-group">
                @for (var i = 0; i < Model.AmenitiesList.Count(); i++)
                    {
                        @Html.CheckBoxFor(m => m.AmenitiesList[i].IsChecked, new { @class = "form-control" });
                        <label>@Model.AmenitiesList[i].amenityType</label>
                             //If you need to hide any values and get them in your post
                        @Html.HiddenFor(m => m.AmenitiesList[i].AmenityId)
                        @Html.HiddenFor(m => m.AmenitiesList[i].AmenityPrice)
                    }
            </div>

这是我的视图模型

public class BookingRoom
    {
        public Bookings bookings { get; set; }
        public Rooms rooms { get; set; }
        public List<Amenities> AmenitiesList { get; set; } = new List<Amenities>();
    }

这是我的设施模型

public class Amenities
    {
        [Key]
        public int AmenityId { get; set; }
        public double AmenityPrice { get; set; }
        public AmenityType amenityType { get; set; }
        public bool IsChecked { get; set; }
    }

    public enum AmenityType
    {
        tv,
        wi_fi,
        hair_dryer,
        help
    }

标签: c#entity-frameworknullreferenceexception

解决方案


查询时你也应该包含它AmenitiesList,否则它将为空:

在控制器中:

var bookingRoom = context.BookingRooms.Include(b => b.AmenitiesList).FirstOrDefault(b => b.Id == someId);
//                                    ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^

请注意,我查询的可能不是您想要的,只是为了演示如何使用Include(),您还应该添加using Microsoft.EntityFrameworkCore.


推荐阅读