导航属性未加载 - 急切加载

时间:2018-02-05 18:47:49

标签: entity-framework-6 eager-loading

我对实体框架没什么经验。我正在尝试使用Eager Loading,但似乎我做错了。

虽然我正在使用" include"在我的查询中,导航属性"主题"部门课程,没有加载。

下面你可以找到2 POCO,DBContext和Main方法。

输出只是部门的标题("计算机科学"),而不是显示相关主题(" Java"," C#",& #34; C ++"。)

public class Department
{
    public Department()
    {
        Subjects = new HashSet<Subject>();
    }

    public int ID { get; set; }
    public string Title { get; set; }

    public  ICollection<Subject> Subjects { get; set; }

}


 public class Subject
{
    public Subject()
    {
        aDepartment = new Department();
    }
    public int ID { get; set; }
    public string Title { get; set; }
    public int DepartmentID { get; set; }

    public  Department aDepartment { get; set; }        
}

   public class ModelDB : DbContext
{
    public ModelDB() : base("name=ModelDB")
    {
        Configuration.LazyLoadingEnabled = false;
       Configuration.ProxyCreationEnabled = true;
    }

    public DbSet<Department> Departments { get; set; }
    public DbSet<Subject> Subjects { get; set; }

}


static void Main(string[] args)
    {
        ModelDB db = new ModelDB();
        /*
        Department dep = new Department() { ID = 1, Title = "Computer Science" };
        db.Departments.Add(dep);
        db.SaveChanges();


        Subject s1 = new Subject() { ID=1, Title="Java", aDepartment = dep };
        db.Subjects.Add(s1);
        db.SaveChanges();

        Subject s2 = new Subject() { ID = 2, Title = "C#", aDepartment = dep };

        db.Subjects.Add(s2);
        db.SaveChanges();

        Subject s3 = new Subject() { ID = 3, Title = "C++", aDepartment=dep };
        db.Subjects.Add(s3);
        db.SaveChanges();
        */
        var lstDepartments = db.Departments.Include("Subjects");

        foreach (var d in lstDepartments)
        {

            Console.WriteLine(d.Title);
            var ss = d.Subjects;
            foreach(var s in ss)
            {
                Console.WriteLine(s.Title);
            }
        }

        Console.WriteLine("Press any key to exit...");
        Console.ReadKey();

    }

2 个答案:

答案 0 :(得分:2)

主要问题是您正在初始化引用导航属性(aDepartment = new Department();),这会使EF基础架构混乱并阻止其正常工作。初始化集合导航属性是可以的(尽管不是强制性的),但从不对参考导航属性执行此操作。

Subject构造函数中删除上述行将解决此问题。另外,虽然它在某种程度上适用于您的情况(令我惊讶的是),但最好遵循命名约定并且不要调用导航属性aDepartment,而只需调用Department以与DepartmentID对齐FK财产。

以下是Subject实体的更正后的工作版本:

public class Subject
{
    public int ID { get; set; }
    public string Title { get; set; }
    public int DepartmentID { get; set; }
    public Department Department { get; set; }
}

答案 1 :(得分:0)

我觉得你可能没有告诉EF外键是什么。告诉EF这个链接的映射类在哪里?如果您没有这个,请在​​主题上的部门导航属性上方添加[ForeignKey(“DepartmentID”)]属性,看看是否能解决您的问题,是否新部门。 :)