【问题标题】:Entity framework Find result vs LINQ result实体框架查找结果与 LINQ 结果
【发布时间】:2013-03-01 05:58:45
【问题描述】:

我是一名新的 .NET 开发人员。我有 2 个这样的实体类

public class Student
{
    public int userId { get; set; }
    public string username { get; set; }
    public string firstname { get; set; }
    public string lastname { get; set; }
    public string email { get; set; }
    public Course course { get; set; }
}

public class Course
{
    [Key]
    public int courseId { get; set; }
    public String courseName { get; set; }
}

我正在使用这样的数据库上下文对象

using (MyDbContext db = new MyDbContext())

当我使用

访问学生对象时
Student stdent = db.students.Find(1);

student对象中原生类型(int,string)的成员变量包含值,但是类型(Course)的课程变量返回null。

然而,当我使用

var result = from student in db.students where student.userId == 1 select student;

结果包含所有成员变量的值(此处存在整个课程对象)

这是预期的行为还是我遗漏或忽略了什么?

我什至在我的数据库上下文中添加了这个构造函数来禁用延迟加载,但没有帮助

    public MyDbContext() : base()
    {
        this.Configuration.LazyLoadingEnabled = false;
    }

【问题讨论】:

    标签: c# asp.net entity-framework


    【解决方案1】:

    这里发生的情况是,在第一种情况(查找)中,您从数据库中获取一个对象。 Course 不是延迟加载,所以Course 引用是null

    在第二种情况下,您只是定义了一个查询,而不是执行它。我假设您在之后遍历结果,同时检查Course 是否存在。这会导致 Course 被加载,因为您在执行时访问了 Course 导航属性,它已成为查询的一部分。

    如果你这样做了

    var s = (from student in db.students where student.userId == 1 select student)
            .Single();
    

    您会注意到Course 是空的,因为在执行查询时(Single 语句)在没有引用Course 的情况下获取了学生。

    【讨论】:

    • 在第一种情况下,即使我将延迟加载设置为 false(正如我在问题中所说)并尝试访问课程,它仍然给我 null。知道为什么会这样。
    • 是的,它永远不会延迟加载,因为该属性不是虚拟的。与上下文的延迟加载设置无关。它仅由 eager loading 加载。也就是说,通过Include 或通过Students.Select(s => s.Course) 之类的linq 查询或Load 方法对其进行寻址。
    • 我认为您的部分困惑是“lazy = false”的反面(在上下文级别)并不意味着“eager = true”。如果可能,使用“lazy=true”会发生延迟加载(即使用virtual 属性)。除非我上面提到的三个选项明确要求,否则使用 "lazy=false" no 加载将发生。
    • 谢谢。这澄清了很多事情
    【解决方案2】:

    延迟加载仅加载初始对象。为了获得第二个选项来检索课程信息,您需要在加载选项中指定。

    DataLoadOptions dataLoadOptions = new DataLoadOptions();
    dataLoadOptions.LoadWith<Customer>(c => c.Course);
    db.LoadOptions = dataLoadOptions;
    
    Student stdent = db.students.Find( c=>c.userid == 1).FirstOrDefault();
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-01-11
      • 2011-12-18
      • 2011-08-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多