实体框架linq查询Include()多个子实体

这可能是一个非常重要的问题,但是当编写跨越三个级别(或更多)的查询时,包含多个子实体的好方法是什么?


即我有4个表:Company,Employee,Employee_Car和Employee_Country


公司与员工有1:m的关系。


Employee与Employee_Car和Employee_Country的关系为1:m。


如果我想编写一个返回所有4个表中数据的查询,我目前正在编写:


Company company = context.Companies

                         .Include("Employee.Employee_Car")

                         .Include("Employee.Employee_Country")

                         .FirstOrDefault(c => c.Id == companyID);

必须有一个更优雅的方式!这是漫长的缠绕,并产生可怕的SQL


我在VS 2010中使用EF4


慕哥9229398
浏览 2711回答 3
3回答

慕容3067478

使用扩展方法。将NameOfContext替换为对象上下文的名称。public static class Extensions{&nbsp; &nbsp;public static IQueryable<Company> CompleteCompanies(this NameOfContext context){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;return context.Companies&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.Include("Employee.Employee_Car")&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.Include("Employee.Employee_Country") ;&nbsp; &nbsp; &nbsp;}&nbsp; &nbsp; &nbsp;public static Company CompanyById(this NameOfContext context, int companyID){&nbsp; &nbsp; &nbsp; &nbsp; &nbsp;return context.Companies&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.Include("Employee.Employee_Car")&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.Include("Employee.Employee_Country")&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.FirstOrDefault(c => c.Id == companyID) ;&nbsp; &nbsp; &nbsp; }}然后你的代码变成了&nbsp; &nbsp; &nbsp;Company company =&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; context.CompleteCompanies().FirstOrDefault(c => c.Id == companyID);&nbsp; &nbsp; &nbsp;//or if you want even more&nbsp; &nbsp; &nbsp;Company company =&nbsp;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; context.CompanyById(companyID);
打开App,查看更多内容
随时随地看视频慕课网APP