gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 21:56:12 24 4
gpt4 key购买 nike

我正在按照此 tutorial 使用 MVC 5 学习 EF6 .我知道可能有人问过这个问题,但我不确定我到底需要寻找什么?我检查了数据库,数据在那里?谁能指出我正确的方向?

我有一个问题,在我的 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; }

异常:

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

最佳答案

如果您想延迟加载,您需要将导航属性更改为 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; }
}

检查这个post为了更好的解释。当您使用 POCO 实体类型时,延迟加载是通过创建派生代理类型的实例然后覆盖 virtual 属性以添加加载 Hook 来实现的。

关于c# - 模型属性返回 null,但值存在于 db MVC5 EF 中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31686865/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com