实体框架linq查询包含()多个子实体 [英] 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个表:公司
,员工
, Employee_Car
和 Employee_Country
公司与Employee有1:m的关系。
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
推荐答案
使用扩展方法。
将 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查询包含()多个子实体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!