You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C#中使用GraphQL/HotChocolate实现通用查询

泛型Query类实现提示与说明

当前代码的核心问题

你现在的Query<TEntity>类里的GetCountries方法命名不符合泛型类的通用性——这个类是为所有实体类型设计的,方法名却绑定了Country实体,应该改成通用名称,比如GetAll。

优化后的基础实现示例

public class Query<TEntity> where TEntity : class
{
    private readonly IGenericRepository<TEntity> _genericRepository;

    public Query(IGenericRepository<TEntity> genericRepository)
    {
        _genericRepository = genericRepository;
    }

    // 获取当前实体类型的所有数据
    public List<TEntity> GetAll()
    {
        return _genericRepository.GetAll();
    }
}

扩展实现的关键提示

  • 通用方法命名:所有方法名要适配任意TEntity,避免出现GetCountries、GetUsers这类绑定特定实体的名称,改用GetAll、GetById、GetWhere这类通用命名。
  • 添加动态过滤能力:利用LINQ表达式树实现条件查询,比如新增方法:
    public List<TEntity> GetWhere(Expression<Func<TEntity, bool>> predicate)
    {
        return _genericRepository.GetWhere(predicate);
    }
    
  • 支持排序与分页:为查询添加排序、分页参数,满足实际业务场景的需求,示例方法:
    public List<TEntity> GetPaged(int pageIndex, int pageSize, Expression<Func<TEntity, object>> sortBy, bool isAscending = true)
    {
        return _genericRepository.GetPaged(pageIndex, pageSize, sortBy, isAscending);
    }
    
  • 适配依赖注入:确保IGenericRepository<TEntity>已在DI容器中正确注册,这样每个实体对应的Query<TEntity>实例都能自动获取到对应的仓储实现。
  • 保持单一职责:Query类只负责封装查询逻辑,不要包含增删改操作,把修改逻辑放到单独的Command类中,遵循CQRS原则(可选但推荐)。

仓储层配套要求

如果你的IGenericRepository<TEntity>还没有实现上述扩展方法,需要先在仓储层完善对应的逻辑,比如在仓储类中用LINQ实现过滤、排序、分页:

public class GenericRepository<TEntity> : IGenericRepository<TEntity> where TEntity : class
{
    private readonly DbContext _dbContext;
    private readonly DbSet<TEntity> _dbSet;

    public GenericRepository(DbContext dbContext)
    {
        _dbContext = dbContext;
        _dbSet = dbContext.Set<TEntity>();
    }

    public List<TEntity> GetAll()
    {
        return _dbSet.ToList();
    }

    public List<TEntity> GetWhere(Expression<Func<TEntity, bool>> predicate)
    {
        return _dbSet.Where(predicate).ToList();
    }

    public List<TEntity> GetPaged(int pageIndex, int pageSize, Expression<Func<TEntity, object>> sortBy, bool isAscending = true)
    {
        var query = _dbSet.AsQueryable();
        query = isAscending ? query.OrderBy(sortBy) : query.OrderByDescending(sortBy);
        return query.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToList();
    }

    public TEntity GetById(int id)
    {
        return _dbSet.Find(id);
    }
}

内容的提问来源于stack exchange,提问作者Oxygen

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.23 17:13:35