【问题标题】:How to make dynamic inclusion of navigation properties?如何动态包含导航属性?
【发布时间】:2019-04-29 07:12:21
【问题描述】:

我有一个小问题。 假设这样的实体

public class FirstEntity
{
    public int ID { get; set; }
    public string Prop1 { get; set; }
    public string Prop2 { get; set; }
    public virtual ICollection<SecondEntity> SecondECollection { get; set; }
}

public class SecondEntity
{
    public int ID { get; set; }
    public string Prop1 { get; set; }
    public virtual ThirdEntity Third { get; set; }
}

在存储库中,要获取具有所有导航属性的实体,我必须这样做

public IQueryable<FirstEntity> Get()
{
    return 
        _context.Set<FirstEntity>()
            .Select(t => t)
            .Include(t => t.SecondECollection)
            .ThenInclude(t => t.ThirdEntity);
}

这很好,但是,在现实世界中,我有一些存储库,我必须在每个 repo 中都这样做,我想动态化。 对于包含我已经在 BaseRepository 中执行此操作(我的所有存储库都继承自此)并且它工作正常

public IQueryable<TEntity> GetBySpecification(ISpecification<TEntity> spec = null, bool tracking = true, params Expression<Func<TEntity, object>>[] includeExpressions)
{
    var query = _context.Set<TEntity>().Select(r => r);
    if (!tracking)
        query = query.AsNoTracking();
    if (includeExpressions != null)
        foreach (var includeExpression in includeExpressions)
            query = query.Include(includeExpression);
    if (spec != null)
        query = query.Where(spec.Expression);
    return query;
}

但是我如何动态地制作 ThenInclude? 有什么建议么? 谢谢! p.s.:对不起,我的英语......

【问题讨论】:

    标签: c# ef-core-2.0


    【解决方案1】:

    使用Func&lt;IQueryable&lt;TEntity&gt;, IQueryable&lt;TEntity&gt;&gt; 进行参数化。

    您可以简单地使用.AsQueryable(),而不是.Select(r =&gt; r)

    public IQueryable<TEntity> GetBySpecification(ISpecification<TEntity> spec = null, bool tracking = true, params Func<IQueryable<TEntity>, IQueryable<TEntity>>[] includes)
    {
        var query = _context.Set<TEntity>().AsQueryable();
        if (!tracking)
            query = query.AsNoTracking();
        if (includes != null)
            foreach (var include in includes)
                query = include(query);
        if (spec != null)
            query = query.Where(spec.Expression);
        return query;
    }
    
    return GetBySpecification(
        includes: new Func<IQueryable<User>, IQueryable<User>>[]
        {
            (q) => q.Include(u => u.Roles).ThenInclude(r => r.Permissions),
        });
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-23
      • 1970-01-01
      • 1970-01-01
      • 2015-12-23
      • 1970-01-01
      • 2021-11-06
      • 2019-12-17
      • 2013-07-11
      相关资源
      最近更新 更多