我正在使用 MVC 5 学习 EF6 tutorial 。我知道可能有人问过这个问题,但我不确定我到底需要寻找什么?我检查了数据库,数据在那里?谁能指出我正确的方向?
我有一个问题,在我的 Model.Enrollments 中为空(此 View 采用学生模型),但是在数据库中它显示它在该表中具有值。
型号:学生
public int ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public ICollection<Enrollment> Enrollments { get; set; }
类(class)
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; }
异常(exception):
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>();
最佳答案
如果您想延迟加载,则需要将导航属性更改为虚拟
。
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; }
}
检查这个post为了更好的解释。当您使用 POCO 实体类型时,延迟加载是通过创建派生代理类型的实例,然后重写 virtual
属性以添加加载 Hook 来实现的。
关于c# - 模型属性返回 null,但值存在于 db MVC5 EF 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31686865/