实体框架 linq 查询 Include() 多个子实体 [英] Entity framework linq query Include() multiple children entities
问题描述
这可能是一个非常基本的问题,但在编写跨越三个级别(或更多)的查询时,包含多个子实体的好方法是什么?
This may be a really elementry question but whats a nice way to include multiple children entities when writing a query that spans THREE levels (or more)?
即我有 4 个表:Company
、Employee
、Employee_Car
和 Employee_Country
i.e. I have 4 tables: Company
, Employee
, Employee_Car
and Employee_Country
公司与员工是一对一的关系.
Company has a 1:m relationship with Employee.
Employee 与 Employee_Car 和 Employee_Country 有 1:m 的关系.
Employee has a 1:m relationship with both Employee_Car and Employee_Country.
如果我想编写一个返回所有 4 个表中数据的查询,我目前正在编写:
If i want to write a query that returns the data from all 4 the tables, I am currently writing:
Company company = context.Companies
.Include("Employee.Employee_Car")
.Include("Employee.Employee_Country")
.FirstOrDefault(c => c.Id == companyID);
必须有更优雅的方式!这是冗长的并生成可怕的 SQL
There has to be a more elegant way! This is long winded and generates horrendous SQL
我在 VS 2010 中使用 EF4
I am using EF4 with VS 2010
推荐答案
使用 extension方法.将 NameOfContext 替换为您的对象上下文的名称.
Use extension methods. Replace NameOfContext with the name of your object context.
public static class Extensions{
public static IQueryable<Company> CompleteCompanies(this NameOfContext context){
return context.Companies
.Include("Employee.Employee_Car")
.Include("Employee.Employee_Country") ;
}
public static Company CompanyById(this NameOfContext context, int companyID){
return context.Companies
.Include("Employee.Employee_Car")
.Include("Employee.Employee_Country")
.FirstOrDefault(c => c.Id == companyID) ;
}
}
那么你的代码就变成了
Company company =
context.CompleteCompanies().FirstOrDefault(c => c.Id == companyID);
//or if you want even more
Company company =
context.CompanyById(companyID);
这篇关于实体框架 linq 查询 Include() 多个子实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!