【发布时间】:2011-07-19 14:02:35
【问题描述】:
我在 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]);
}
【问题讨论】:
-
详细说明“在查询中包含更多实体” ?你能举个例子吗?如果您有
ObjectContext,您应该能够使用 LinqToEntities 查询对象/或相关对象 -
@giddy:查看上面的更新。谢谢。
标签: c# entity-framework entity-framework-4 repository-pattern ef-code-first