延迟加载在Entity Framework中不起作用 [英] Lazy loading not working in Entity Framework
问题描述
我有两个使用virtual关键字连接的类:
I have two classes that are connected by using the virtual keyword:
学生:
public class Student
{
public int StudentId{get; set;}
public string LastName { get; set; }
public string FirstName { 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 decimal? Grade { get; set; }
public virtual Course course { get; set; }
public virtual Student student { get; set; }
}
两个表均已填充,并具有相应的记录(例如,有一个ID为1的学生,而ID为1的学生的入学率).
Both tables are populated, and have corresponding records (for instance, there is a student with id 1 and enrollments for student with id 1).
我要通过其ID来吸引学生并将其发送到视图
I'm pulling up a student by it's id and sending it to a view
Student student = db.Students.Find(id);
return View(student);
在视图中,我可以显示该学生的详细信息. @Model
确实包含一个Enrollment
属性(至少它以智能感知出现并且没有出现红线),但是它是Null
.
In the view I can display the details for that student. The @Model
does contain an Enrollment
property (at least it comes up in intellisense and doesn't red-line), but it is Null
.
还有一门课程:
{
public int CourseId { get; set; }
public String CourseName { get; set; }
public int TotalCredits { get; set; }
}
由于@Model.Enrollments
是Null
,所以我无法访问@Model.Enrollment.CourseNamae
.
Since @Model.Enrollments
is Null
, I can't access @Model.Enrollment.CourseNamae
.
我只是尝试了一种黑客解决方法:
I just tried a hack workaround:
IEnumerable<Student> temp = db.Students.Include(s => s.Enrollments);
Student student = temp.FirstOrDefault(s => s.StudentId.Equals(id));
return View(student);
这在第二行给了我错误:
This is giving me the error on the second line:
System.InvalidOperationException:指定的包含路径无效. EntityType'MyFirstProject2.Models.Student'未声明名称为'Enrollments'的导航属性.
System.InvalidOperationException: A specified Include path is not valid. The EntityType 'MyFirstProject2.Models.Student' does not declare a navigation property with the name 'Enrollments'.
有什么线索吗?
推荐答案
有点晚了,但是在 还有延迟加载规则:
- context.Configuration.ProxyCreationEnabled应该为true.
- context.Configuration.LazyLoadingEnabled应该为true.
- 导航属性应定义为公共的,虚拟的.如果属性未定义为,上下文将不会延迟加载 虚拟的.
- context.Configuration.ProxyCreationEnabled should be true.
- context.Configuration.LazyLoadingEnabled should be true.
- Navigation property should be defined as public, virtual. Context will NOT do lazy loading if the property is not define as virtual.
编辑: 关系使用的最后一件事:
EDIT: One last thing for relationships use:
public virtual ICollection<Enrollment> Enrollments { get; set; }
其他链接:
这篇关于延迟加载在Entity Framework中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!