延迟加载在Entity Framework中不起作用 [英] Lazy loading not working in Entity Framework

查看:132
本文介绍了延迟加载在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.EnrollmentsNull,所以我无法访问@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'.

有什么线索吗?

推荐答案

有点晚了,但是在 还有延迟加载规则:

  1. context.Configuration.ProxyCreationEnabled应该为true.
  2. context.Configuration.LazyLoadingEnabled应该为true.
  3. 导航属性应定义为公共的,虚拟的.如果属性未定义为,上下文将不会延迟加载 虚拟的.
  1. context.Configuration.ProxyCreationEnabled should be true.
  2. context.Configuration.LazyLoadingEnabled should be true.
  3. 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆