本文介绍了如何动态包含导航属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

这项工作正常,但是,在现实世界中,我有一些存储库,并且我必须在每个回购中都这样做,并且我想使其动态化.对于Include,我已在BaseRepository中进行了此操作(我的所有存储库均从此继承),并且工作正常

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

但是我如何才能动态地制作ThenInclude?有什么建议么?谢谢!附言:抱歉,我的英语...

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

推荐答案

使用 Func< IQueryable< TEntity>,IQueryable< TEntity>>> 进行参数化.

您可以简单地使用 .AsQueryable()来代替 .Select(r => r).

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

这篇关于如何动态包含导航属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 18:54