Shimmy Weitzhandler
Shimmy Weitzhandler

Reputation: 104731

Reduce massive includes in EF

Any ways to shorten this include statement?

var query = Context.Businesses
 .Include(b => b.Categories)
 .Include(b => b.Branches.Select(br => br.Address))
 .Include(b => b.Branches.Select(br => br.BranchType))
 .Include(b => b.Branches.Select(br => br.CustomFields))
 .Include(b => b.Branches.Select(br => br.Phones))
 .Include(b => b.Branches.Select(br => br.OpeningTimes.Select(ot => ot.WorkingPeriods)));

I thought about using a SPROC but I'm unsure how it will know what was returned.

So is there a non hard-coded way to do this shorter than it is? Perhaps an external lambda that treats all the properties of Branch?

Upvotes: 1

Views: 195

Answers (1)

greg84
greg84

Reputation: 7609

You could do something similar to the answer to this question. So in your case, make an extension method like this:

public static class DataContextExtensions
{
   public static IQueryable<Business> BusinessesComplete(this DataContext context){
         return context.Businesses
             .Include(b => b.Categories)
             .Include(b => b.Branches.Select(br => br.Address))
             .Include(b => b.Branches.Select(br => br.BranchType))
             .Include(b => b.Branches.Select(br => br.CustomFields))
             .Include(b => b.Branches.Select(br => br.Phones))
             .Include(b => b.Branches.Select(br => br.OpeningTimes.Select(ot => ot.WorkingPeriods)));
     }
}

Then use it like this:

Business business = context.BusinessesComplete().Where(b => ...etc);

Upvotes: 1

Related Questions