c# - EF 包括其他实体(通用存储库模式)

标签 c# entity-framework entity-framework-4 repository-pattern ef-code-first

我在 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/

相关文章:

c# - Linq to Entities over SQL Server 2005 上的 EF 4

c# - 将游戏对象移动/转移到另一个场景

c# - 无法在 unity 5.6 中导入 Fabric

c# - Aes 加密 MemoryStream.ToArray 为空

c# - 使用 ASP.Net 和 Entity Framework : adding a child object in a 1:1 relationship

sql-server - Entity Framework 4 与 LINQ to SQL,适用于中小型应用程序,与 SQL Server 配合使用

c# - 当我用 C# 将一个 csv 文件放入 Sql Server 时,有些字段写错了?

c# - 从 EF4 升级后在 EF6 中查询数据的 Null Reference Exception

SQL Server 对象资源管理器不显示当前数据库

entity-framework - Entity Framework - 从导航属性中删除虚拟关键字