How to make dynamic inclusion of navigation properties?

女生的网名这么多〃 提交于 2019-12-30 14:56:54

问题


I've a little problem. Assuming a Entity like this

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; }
}

In repository, to get the entity with all the navigation properties i've to do something like this

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

This work fine, but, in real world i've some repositories and i've to do this in every repo, and i would like to make dynamic. For the Include i've do this in a BaseRepository (all my repos inherit from this) and it's work fine

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;
}

But how i can make dynamically the ThenInclude? Any suggestions? Thanks! p.s.: sorry form my english...


回答1:


Parameterize with a Func<IQueryable<TEntity>, IQueryable<TEntity>>.

And instead of .Select(r => r) you can simply use .AsQueryable().

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),
    });


来源:https://stackoverflow.com/questions/55898559/how-to-make-dynamic-inclusion-of-navigation-properties

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!