EF Eager加载包括多个

时间:2014-01-16 13:19:44

标签: c# entity-framework eager-loading

我有这个存储库:

public class Repository<T> : IRepository<T> where T : class
{
    private readonly DbContext context;
    private readonly DbSet<T> dbEntitySet;

    public Repository(DbContext context)
    {
        if (context == null)
            throw new ArgumentNullException("context");

        this.context = context;
        this.dbEntitySet = context.Set<T>();
    }

    public IEnumerable<T> GetAll()
    {
        return this.dbEntitySet;
    }

    public IEnumerable<T> GetAll(string include)
    {
        return this.dbEntitySet.Include(include);
    }

    public IEnumerable<T> GetAll(string[] includes)
    {
        IQueryable<T> query = context.Set<T>();
        foreach (var include in includes)
            query.Include(include);

        return query;
    }

    public void Create(T model)
    {
        this.dbEntitySet.Add(model);
    }

    public void Update(T model)
    {
        this.context.Entry<T>(model).State = EntityState.Modified;
    }

    public void Remove(T model)
    {
        this.context.Entry<T>(model).State = EntityState.Deleted;
    }

    public void Dispose()
    {
        this.context.Dispose();
    }
}

我有一个看起来像这样的服务:

public class Service<T> where T : class
{
    private readonly IRepository<T> repository;

    protected IRepository<T> Repository
    {
        get { return this.repository; }
    }

    internal Service(IUnitOfWork unitOfWork)
    {
        this.repository = unitOfWork.GetRepository<T>();
    }
}

我的网页服务看起来像这样(简化):

public class PageService : Service<Page>
{

    // ...

    public IList<Page> GetPublished()
    {
        return this.Repository.GetAll(new string[] { "ForbiddenUsers", "ForbiddenGroups" }).Where(model => model.Published).ToList();
    }

    // ...

}

为了清楚起见,我的 Page 看起来像这样:

public enum PageType
{
    Root,
    System,
    Page,
    Link,
    Group
}

public partial class Page
{
    public int Id { get; set; }
    public System.DateTime DateCreated { get; set; }
    public string CreatedById { get; set; }
    public Nullable<System.DateTime> DateModified { get; set; }
    public string ModifiedById { get; set; }
    public string CompanyId { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public string FileName { get; set; }

    public string Path { get; set; }
    public string ViewData { get; set; }
    public string ViewTitle { get; set; }

    public string Link { get; set; }
    public bool Published { get; set; }
    public PageType Type { get; set; }
    public int Order { get; set; }
    public string Lineage { get; set; }
    public Nullable<int> ParentId { get; set; }
    public bool Restricted { get; set; }
    public bool Deleted { get; set; }

    public Company Company { get; set; }
    public User CreatedBy { get; set; }
    public User ModifiedBy { get; set; }
    public Page Parent { get; set; }
    public MenuPage MenuPage { get; set; }
    public ICollection<Page> Pages { get; set; }
    public ICollection<User> ForbiddenUsers { get; set; }
    public ICollection<Group> ForbiddenGroups { get; set; }
}

运行此代码时, ForbiddenUsers ForbiddenGroups 始终为null。 如果我检查调用堆栈,我可以看到生成的查询如下所示:

SELECT 
[Extent1].[Id] AS [Id], 
[Extent1].[DateCreated] AS [DateCreated], 
[Extent1].[CreatedById] AS [CreatedById], 
[Extent1].[DateModified] AS [DateModified], 
[Extent1].[ModifiedById] AS [ModifiedById], 
[Extent1].[CompanyId] AS [CompanyId], 
[Extent1].[Name] AS [Name], 
[Extent1].[Description] AS [Description], 
[Extent1].[FileName] AS [FileName], 
[Extent1].[Path] AS [Path], 
[Extent1].[ViewData] AS [ViewData], 
[Extent1].[ViewTitle] AS [ViewTitle], 
[Extent1].[Link] AS [Link], 
[Extent1].[Published] AS [Published], 
[Extent1].[Type] AS [Type], 
[Extent1].[Order] AS [Order], 
[Extent1].[Lineage] AS [Lineage], 
[Extent1].[ParentId] AS [ParentId], 
[Extent1].[Restricted] AS [Restricted], 
[Extent1].[Deleted] AS [Deleted]
FROM [dbo].[Pages] AS [Extent1]

如您所见,这完全忽略了我的包含。

如果我将服务方法更改为:

public IList<Page> GetPublished()
{
    return this.Repository.GetAll("ForbiddenUsers").Where(model => model.Published).ToList();
}

并运行我的代码, ForbiddenUsers 现在已填充,调用堆栈显示正确生成的查询(太大而无法在此处粘贴)。

我需要允许多个包含但我无法弄清楚它们为什么不起作用....

任何帮助都将非常感谢....

3 个答案:

答案 0 :(得分:7)

您应该将包含的查询分配回查询变量,因为QueryableExtensions.Include会创建新的DbQuery<T>而不是修改现有的params。另外,我建议您将public IEnumerable<T> GetAll(params string[] includes) { IQueryable<T> query = context.Set<T>(); foreach (var include in includes) query = query.Include(include); return query; } 用于包含的路径:

public IList<Page> GetPublished()
{
    return Repository.GetAll("ForbiddenUsers", "ForbiddenGroups")
                     .Where(model => model.Published)
                     .ToList();
}

这将允许您传递所有包含的路径而不显式创建数组:

{{1}}

答案 1 :(得分:2)

尝试

   foreach (var include in includes)
        query = query.Include(include);

    return query;

答案 2 :(得分:0)

下面是C#6中的一个例子。此外,请注意使用 nameof 运算符来使代码更易于维护,以便在重命名时不需要手动更新属性名称的字符串值。

// Assign the property names
var navigablePropertyNames = new[]
{
    nameof(ParentEntity.Id),
    nameof(ParentEntity.Name),
    nameof(ParentEntity.Description)
};

// Do the inclusion
GetAll(navigablePropertyNames);

因此,根据您的具体要求:

public IEnumerable<T> GetAll(params string[] inclusions)
{
    var qry = this.dbEntitySet.AsQueryable();

    foreach(var inclusion in inclusions)
    {
        qry  = qry.Include(inclusion);
    }

    return qry;
}

用途:

// either 
var resultSet1 = GetAll(nameof(ParentEntity.Id),
    nameof(ParentEntity.Name),
    nameof(ParentEntity.Description));

// or
var propertyNames = new[] {
    nameof(ParentEntity.Id),
    nameof(ParentEntity.Name),
    nameof(ParentEntity.Description)};

var resultSet2 = GetAll(propertyNames);