【问题标题】:EntityFramework fluent API "grandchild" relationship mappingEntityFramework fluent API“孙子”关系映射
【发布时间】:2011-12-12 23:35:31
【问题描述】:

我正在尝试映射 EF fluent API 中看似非常常见的情况,但遇到了困难。我有以下课程:

public class Company
{
    public int Id { get; set; }
    public virtual List<Division> Divisions { get; set; }
    public virtual List<Employee> Employees { get; set; }
}
public class Division
{
    public int Id { get; set; }
    public virtual List<Employee> Employees { get; set; }
    public virtual Company Company { get; set; }
}
public class Employee
{
    public int Id { get; set; }
    public string Name { get; set; }
    public virtual Division Division {get; set;}
}

有以下表格:

公司
ID - 整数

部门:
ID - 整数 CompanyId int (FK)

员工
ID - 整数
名称 - varchar(50)
DivisionId - int (FK)

如果 Employee 表有一个 CompanyID FK,这个映射将非常简单:

HasMany(c=>c.Employees).WithRequired().HasForeignKey(e=>e.CompanyId);

但是,由于我没有从 Employee 表到 Company 表的直接 FK,我似乎无法映射 Company 对象中的 Employees 属性以进行延迟加载。

我错过了什么?

【问题讨论】:

    标签: .net entity-framework fluent database-first ef-database-first


    【解决方案1】:

    你无法映射它。 EF 代码首先只能映射物理关系。因此,如果您的员工没有CompanyId FK,它也与Company 表没有物理关系。作为一种解决方法,您可以使用非映射属性:

    public class Company
    {
        public int Id { get; set; }
        public virtual List<Division> Divisions { get; set; }
    
        public IEnumerable<Employee> Employees 
        {
            get
            {
                return Divisions.SelectMany(d => d.Employees);
            }
        }
    }
    

    此解决方案无法解决您对延迟加载的要求(但会以糟糕的方式)。在没有加载关系的情况下调用Employees 将执行查询以延迟加载Divisions,然后它将调用单独的延迟加载查询来为每个Employees 加载Employees = N + 1 个问题。所以只能在急切加载时使用它。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2016-10-31
      • 1970-01-01
      • 1970-01-01
      • 2015-07-27
      • 1970-01-01
      • 2012-12-01
      • 1970-01-01
      相关资源
      最近更新 更多