Search code examples
linqentity-frameworklazy-loading

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)?

i.e. I have 4 tables: Company, Employee, Employee_Car and Employee_Country

Company has a 1:m relationship with Employee.

Employee has a 1:m relationship with both Employee_Car and Employee_Country.

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);

There has to be a more elegant way! This is long winded and generates horrendous SQL

I am using EF4 with VS 2010


Solution

  • 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) ;
          }
    
    }
    

    Then your code becomes

         Company company = 
              context.CompleteCompanies().FirstOrDefault(c => c.Id == companyID);
    
         //or if you want even more
         Company company = 
              context.CompanyById(companyID);