通用存储库功能的使用

usage of generic repository function

我是 EF Core 的新手。以下是我要获取的存储库函数:

public async Task<IReadOnlyList<T>> GetAsync(Expression<Func<T, bool>> predicate = null, Func<IQueryable<T>, IOrderedQueryable<T>> orderBy = null, string includeString = null, bool disableTracking = true)
{
    IQueryable<T> query = _dbContext.Set<T>();
    if (disableTracking) query = query.AsNoTracking();

    if (!string.IsNullOrWhiteSpace(includeString)) query = query.Include(includeString);

    if (predicate != null) query = query.Where(predicate);

    if (orderBy != null)
        return await orderBy(query).ToListAsync();
    return await query.ToListAsync();
}

public async Task<IReadOnlyList<T>> GetAsync(Expression<Func<T, bool>> predicate = null, Func<IQueryable<T>, IOrderedQueryable<T>> orderBy = null, List<Expression<Func<T, object>>> includes = null, bool disableTracking = true)
{
    IQueryable<T> query = _dbContext.Set<T>();
    if (disableTracking) query = query.AsNoTracking();

    if (includes != null) query = includes.Aggregate(query, (current, include) => current.Include(include));

    if (predicate != null) query = query.Where(predicate);

    if (orderBy != null)
        return await orderBy(query).ToListAsync();
    return await query.ToListAsync();
}

我知道如何设置过滤条件。我的问题是:如何调用 Include 和 OrderBy?

工作示例:

GetAsync(x => x.Name.ToLower().Contains(productName.ToLower()))

include 不需要参数。如果您在数据库中有关系,则可以将其用于包含。它会自动获取所有 table(与您的主 table 链接)。

foreach (var property in _dbContext.Model.FindEntityType(typeof(T)).GetNavigations())
    query = query.Include(property.Name);

像这样。

public async Task<IReadOnlyList<T>> GetAsync(Expression<Func<T, bool>> predicate = null, Func<IQueryable<T>, IOrderedQueryable<T>> orderBy = null, bool disableTracking = true)
    {
        IQueryable<T> query = _dbContext.Set<T>();
        if (disableTracking) query = query.AsNoTracking();

        foreach (var property in _dbContext.Model.FindEntityType(typeof(T)).GetNavigations())
            query = query.Include(property.Name);

        if (predicate != null) query = query.Where(predicate);

        if (orderBy != null)
            return await orderBy(query).ToListAsync();
        return await query.ToListAsync();
    }

通用存储库

**

控制器

**