减少EF中的大量包含

时间:2013-04-24 11:54:02

标签: entity-framework include

任何缩短此方法的方法都包括声明?

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

我考虑过使用SPROC,但我不确定它将如何知道返回的内容。

那么有一种非硬编码的方式可以做到这么短吗?也许是一个外部lambda,它处理Branch的所有属性?

1 个答案:

答案 0 :(得分:1)

您可以执行与this question的答案类似的操作。所以在你的情况下,做一个像这样的扩展方法:

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

然后像这样使用它:

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