我正在尝试在mvc官方网站上给出的Mvc示例。这里我有3个模型:学生,课程和注册,其中课程和注册实体是一对多的关系,注册和学生是多对一的关系。
学生、课程和注册的模型如下所示,导航属性被标记为"virtual“,因为我需要执行惰性绑定
public class Student
{
public int StudentID { get;set; }
public string LastName { get; set; }
public string FirstMidName { get; set; }
public DateTime EnrollmentDate { get; set; }
public virtual IEnumerable<Enrollment> Enrollments { get; set; }
}以同样的方式我有我的课程模型
我的注册模型
public class Enrollment
{
public int EnrollmentID { get; set; }
public int CourseID { get; set; }
public int StudentID { get; set; }
// public Grade? Grade { get; set; }
public virtual Course Course { get; set; }
public virtual Student Student { get; set; }
}我在EF 5中使用了Code-First技术。
public class SchoolContext:DbContext
{
public DbSet<Student> Students { get; set; }
public DbSet<Enrollment> Enrollments { get; set; }
public DbSet<Course> Courses { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
}
}通过搭建,我已经生成了我所有的视图.On单击我的详细信息操作链接我有一个控制器函数,它被调用
public ActionResult Details(int id = 0)
{
db.Configuration.LazyLoadingEnabled = true;
db.Configuration.ProxyCreationEnabled = true;
Student student = db.Students.Find(id);
// db.Entry(student).Reference(p => p.Enrollments).Load();
IEnumerable<Enrollment> s= student.Enrollments;
if (student == null)
{
return HttpNotFound();
}
return View(student);
}这里的问题是,当在控制器中调用passed.In ()方法时,学生类模型中的导航属性是空的,DB中有对应于id的数据是空的,导航属性没有返回数据(Null)。
发布于 2016-06-10 19:31:56
您必须物化实体,以摆脱查询中当前的延迟加载:
Student student = db.Students.Find(id).ToList();在db.Students.Find(id);=将从动态代理返回生成的对象后,这将在不使用ToList()的情况下解决问题。
第二个问题是你有一个造型错误:
IEnumerable<Enrollment> enrollments = student.Enrollments; // is wrong应该是:
ICollection<State> enrollments = student.Enrollments;或
var enrollments = student.Enrollments;https://stackoverflow.com/questions/37745862
复制相似问题