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

Kas*_*sem 67 c# entity-framework repository-pattern entity-framework-4 ef-code-first

我在Entity Framework Code First上使用Generic Repository模式.一切都工作正常,直到我需要在查询中包含更多实体.我成功地包含了一个实体,但现在我无法弄清楚如何包含多个实体.看看到目前为止我得到了什么:

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));
}
Run Code Online (Sandbox Code Playgroud)

我尝试但没有工作的是将一个字符串数组传递给一个函数,然后尝试在查询之上"追加"包含.我在想,如果我叫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]);
}
Run Code Online (Sandbox Code Playgroud)

Lad*_*nka 133

仅使用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;
}
Run Code Online (Sandbox Code Playgroud)

您将使用它,例如:

var query = context.Customers
                   .IncludeMultiple(
                       c => c.Address,
                       c => c.Orders.Select(o => o.OrderItems));
Run Code Online (Sandbox Code Playgroud)

此查询将使用地址和订单加载所有客户,每个订单将包含其订单商品.

  • 不要使用带字符串的版本.EF 4.1还提供带有lambdas的强类型版本. (3认同)

Shi*_*mmy 5

告别硬编码的 ObjectQuery(T).Include 调用

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