EF包括其他实体(通用存储库模式)

我在entity framework代码优先使用通用存储库模式。 一切工作正常,直到我需要在查询中包含更多的实体。 我成功地包含了一个实体,但现在我不知道如何包含多个实体。 看看我到目前为止:

public IQueryable<TEntity> GetQuery<TEntity>() where TEntity : class { var entityName = GetEntityName<TEntity>(); return _objectContext.CreateQuery<TEntity>(entityName); } public IList<TEntity> GetQueryWithInclude<TEntity>(string toInclude) where TEntity : class { var entityName = GetEntityName<TEntity>(); return _objectContext.CreateQuery<TEntity>(entityName).Include(toInclude).ToList(); } private string GetEntityName<TEntity>() where TEntity : class { return string.Format("{0}.{1}", _objectContext.DefaultContainerName, _pluralizer.Pluralize(typeof(TEntity).Name)); } 

我试图做的,但没有工作是传递一个string数组到一个函数,然后尝试“追加”查询顶部的包括。 我想知道如果我调用GetQueryWithInclude,并一次传递一个实体名称(实际上是一个导航属性)来聚合查询的结果,但我担心这可能会重复每个调用的查询结果…你认为最好的方法是什么?

提前致谢!

更新:

这是我想要实现的一个例子:

 public IQueryable GetQueryWithIncludes(string[] otherEntities) { var entityName = GetEntityName<TEntity>(); //now loop over the otherEntities array //and append Include extensions to the query //so inside the loop, something like: _objectContext.GetQuery<TEntity>(entityName).Include(otherEntities[index]); } 

在IQueryable上只使用Include扩展。 它在EF 4.1程序集中可用。 如果您不想在上层中引用该程序集,请在数据访问程序集中创build包装器扩展方法。

在这里你有例子:

 public static IQueryable<T> IncludeMultiple<T>(this IQueryable<T> query, params Expression<Func<T, object>>[] includes) where T : class { if (includes != null) { query = includes.Aggregate(query, (current, include) => current.Include(include)); } return query; } 

您将使用它,例如:

 var query = context.Customers .IncludeMultiple( c => c.Address, c => c.Orders.Select(o => o.OrderItems)); 

此查询将加载所有客户的地址和订单,每个订单将包含其订单项目。

//我在这里包含了最低限度的内容。 以下是如何使用它。

  IQueryable<File> xg= UnitOfWork.Files.GetAllLazyLoad(d => d.FileId == 1, r => r.FileCategory); //where r.FileCategory is a navigational property. //Interface namespace Msh.Intranet.Repository.GenericRepoPattern { public interface IRepository<T> where T:class { IQueryable<T> GetAllLazyLoad(Expression<Func<T, bool>> filter, params Expression<Func<T, object>>[] children); } } namespace Msh.Intranet.Repository.GenericRepoPattern { /// <summary> /// The EF-dependent, generic repository for data access /// </summary> /// <typeparam name="T">Type of entity for this Repository.</typeparam> public class EFRepository<T> : IRepository<T> where T : class { public EFRepository(DbContext dbContext) { if (dbContext == null) throw new ArgumentNullException("dbContext"); DbContext = dbContext; DbSet = DbContext.Set<T>(); } protected DbContext DbContext { get; set; } protected DbSet<T> DbSet { get; set; } public virtual IQueryable<T> GetAllLazyLoad(Expression<Func<T, bool>> filter, params Expression<Func<T, object>>[] children) { children.ToList().ForEach(x=>DbSet.Include(x).Load()); return DbSet; } } } 

告别硬编码的ObjectQuery(T)。包括调用

如果您使用EF> 4,那么它是内置的,请在MSDN上检查DbExtensions.Include 。