EntityFramework fluent API “grandchild” relationship mapping
-
14-03-2021 - |
문제
I'm trying to map what seems like a very common case in the EF fluent API and have hit a wall. I have the following classes:
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;}
}
With the following tables:
Company
Id - int
Division:
Id - int
CompanyId int (FK)
Employee
Id - int
Name - varchar(50)
DivisionId - int (FK)
If the Employee table had a CompanyID FK, this mapping would be very simple:
HasMany(c=>c.Employees).WithRequired().HasForeignKey(e=>e.CompanyId);
However, since I do not have a direct FK from the Employee table to the Company table, I seem to be unable to map the Employees property in the Company object for lazy loading.
What am I missing?
해결책
You cannot map that. EF code first is only able to map physical relation. So if your employee doesn't have CompanyId
FK it also doesn't have physical relation with Company
table. As a workaround you can use non mapped property:
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);
}
}
}
This solution will not solve your requirement for lazy loading (it will but in terrible way). Calling Employees
without loaded relations will execute query to lazy load Divisions
and after that it will call separate lazy load query to load Employees
for each Division
= N + 1 problem. So use this only with eager loading.