问题描述
|
我在Entity Framework Code First之上使用通用存储库模式。一切工作正常,直到我需要在查询中包含更多实体。我必须成功包含一个实体,但是现在我不知道如何包含多个实体。看看到目前为止我有什么:
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));
}
我试着做但没用的是将字符串数组传递给函数,然后尝试“附加”查询中的包含内容。我想知道是否一次调用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组件中可用。如果您不想在上层引用该程序集,请在数据访问程序集中创建包装器扩展方法。
这里有例子:
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,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,object>>[] children)
{
children.ToList().ForEach(x=>DbSet.Include(x).Load());
return DbSet;
}
}
}
,与硬编码的ObjectQuery(T)告别。
如果您使用的是EF> 4,那么它是内置的,请检查MSDN上的DbExtensions.Include。