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

时间:2015-07-28 20:53:22

标签: c# asp.net-mvc entity-framework

我正在跟随tutorial学习使用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

enter image description here 附加信息:对象引用未设置为对象的实例。

数据库: enter image description here

更新 - 上下文

  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>();

1 个答案:

答案 0 :(得分:3)

如果您想延迟加载,则需要将导航属性更改为var parsed = JObject.Parse(jsonString); JToken token; if (parsed.TryGetValue("Key", out token)) { var value = token.ToString(); ... //Do stuff }

virtual

检查此post以获得更好的解释。当您使用POCO实体类型时,通过创建派生代理类型的实例然后重写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; } } 属性以添加加载钩子来实现延迟加载。