我在 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));
此查询将加载所有客户的地址和订单,每个订单都将包含其订单项目。
关于c# - EF 包括其他实体(通用存储库模式),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5376421/