繁体   English   中英

模型属性返回null,但值存在于db MVC5 EF中

[英]Model property returning null, but value exists in db MVC5 EF

在本教程之后,我将使用MVC 5学习EF6。 我知道可能会问这个问题,但是我不确定我到底需要什么? 我检查了数据库并且数据在那里? 谁能指出我正确的方向?

我有一个问题,在我的Model.Enrollments为null(此视图采用学生模型)中,但是在数据库中它显示该表中有值。

型号: 学生

public int ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
        public ICollection<Enrollment> Enrollments { get; set; }

课程

  public int ID { get; set; }
    public string Title { get; set; }
    public int Credits { get; set; }
    public ICollection<Enrollment> Enrollments { get; set; }

注册

public int ID { get; set; }
public decimal? Grade { get; set; }
public int StudentID { get; set; }
public int CourseID { get; set; }
public Student Student { get; set; }
public Course Course { get; set; }

例外:

An exception of type 'System.NullReferenceException' occurred in App_Web_uycs14gs.dll but was not handled in user code

在此处输入图片说明 附加信息:对象引用未设置为对象的实例。

数据库: 在此处输入图片说明

更新上下文

  public DbSet<Student> Students { get; set; }
       public DbSet<Course> Courses { get; set; }
       public DbSet<Enrollment> Enrollments { get; set; }
       protected override void OnModelCreating(DbModelBuilder modelBuilder)
       {
           modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();

如果要延迟加载,则需要将导航属性更改为virtual

public class Student
{
   //...
   public virtual ICollection<Enrollment> Enrollments { get; set; }
}

public class Course
{
  //...
  public virtual ICollection<Enrollment> Enrollments { get; set; }
}

public class Enrollment
{
  //...
  public virtual Student Student { get; set; }
  public virtual Course Course { get; set; }
}

检查此帖子以获得更好的解释。 当您使用POCO实体类型时,通过创建派生代理类型的实例,然后覆盖virtual属性以添加加载钩子,可以实现延迟加载。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM