Entity Framework 触发查询以加载相关对象,尽管这些对象的显式加载已经完成

Entity Framework fires query to load related object although explicit loading for those objects is already done

我的应用程序中有这些模型和上下文:

      public class Department
   {
     public int Id { get; set; }
     public string Name { get; set;}
     public virtual ICollection<Student> Students { get; set; }
   }

   public class Student
   {
     public int Id { get; set; }

     public string Name { get; set; }

     public virtual Department Department { get; set; }
   }
 public class TestContext : DbContext
{
    public DbSet<Student> Students { get; set; }
    public DbSet<Department> Departments { get; set; }
}

下面是我在 Program.cs class 中的代码:

   class Program
{
    static void Main(string[] args)
    {
        using (var context = new TestContext())
        {
            var students = context.Students.SqlQuery("Select * from dbo.Students").ToList();
            context.Departments.Load();

            Console.WriteLine(students[0].Department.Name); 
            Console.ReadLine(); 
        }
    }
}

虽然相关对象 - 部门通过行 - context.Departments.Load() 加载到上下文中,但当部门名称在控制台中打印时仍然如此 entity framework 在数据库中触发查询以获取相关对象。由于对象已经加载到上下文中,因此不应该触发此相关对象提取查询。 ?

如果我将代码更改为以下 -

            var students = context.Students.ToList(); 
            context.Departments.Load();

            Console.WriteLine(students[0].Department.Name);

然后当你访问学生 [0].Department.Name 时,Ef 不会触发 sql 查询来加载部门 属性。

显然 Change Tracker 关系修复不适用于独立关联和原始 SQL 查询的组合。

要修复只需将外键 属性 添加到学生。例如

public class Student
{
    public int Id { get; set; }

    public string Name { get; set; }

    public int DepartmentId { get; set; }

    public virtual Department Department { get; set; }
}