asp.net 如何在Repository中使用ThenInclude

rur96b6h  于 5个月前  发布在  .NET
关注(0)|答案(1)|浏览(42)

我在使用ThenInclude从数据库中获取高级实体时遇到问题。如何更改GetAll方法来做到这一点?

public class Repository<T> : IRepository<T> where T : class
{
    private readonly ApplicationDbContext _db;
    internal DbSet<T> dbSet;
    public Repository(ApplicationDbContext db)
    {
        _db = db;
        this.dbSet = _db.Set<T>();
    }   

    public IEnumerable<T> GetAll(string? includeProperties = null)
    {
        IQueryable<T> query = dbSet;

        if (!String.IsNullOrEmpty(includeProperties))
        {
            foreach (var property in includeProperties.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
            {
                query = query.Include(property);
            }
        }
        return query.ToList();
    }
}

字符串
我是初学者,如果这个问题很愚蠢,我很抱歉。

3npbholx

3npbholx1#

有几种方法。
第一个是让你的仓库为每种实体类型而特定。这样你就可以包含任何对特定类型有意义的属性。这似乎是Microsoft推荐的模型。
你可以使用一个泛型仓库,但它应该是你的实体特定仓库的基类。这样你就可以在泛型基类中填充通用的东西,同时在派生类中实现任何实体特定的东西,比如包含。
另一种方法是让你的GetAll-方法接受一个Func<IQueryable<T>, IQueryable<T>> includeDecorator,但我可能不推荐这样做,因为我认为这会给调用者带来更多的责任和复杂性。

相关问题