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
CompanyIdFK it also doesn’t have physical relation withCompanytable. As a workaround you can use non mapped property:This solution will not solve your requirement for lazy loading (it will but in terrible way). Calling
Employeeswithout loaded relations will execute query to lazy loadDivisionsand after that it will call separate lazy load query to loadEmployeesfor eachDivision= N + 1 problem. So use this only with eager loading.