我在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 查询对象或相关对象。 - gideon