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

.NET Core中基于通用仓储模式按分类ID获取新闻列表的实现方法

按分类ID获取新闻列表的通用仓储实现方案

问题分析

你当前的代码仅查询了所有关联分类的新闻,但未按分类ID做过滤,因此无法得到指定分类下的新闻列表。

具体实现步骤

1. 确保通用仓储支持过滤参数

如果你的GenericRepository的GetAll方法还不支持过滤表达式,需要先扩展方法(以EF Core为例):

public class GenericRepository<T> where T : class
{
    private readonly DbContext _context;
    private readonly DbSet<T> _dbSet;

    public GenericRepository(DbContext context)
    {
        _context = context;
        _dbSet = context.Set<T>();
    }

    // 支持过滤、导航属性包含的重载方法
    public IEnumerable<T> GetAll(
        Expression<Func<T, bool>> filter = null,
        Func<IQueryable<T>, IIncludableQueryable<T, object>> include = null)
    {
        IQueryable<T> query = _dbSet;

        // 应用过滤条件
        if (filter != null)
        {
            query = query.Where(filter);
        }

        // 加载关联导航属性
        if (include != null)
        {
            query = include(query);
        }

        return query.ToList();
    }
}

2. 按分类ID执行过滤查询

调用仓储方法时,传入过滤条件筛选出关联目标分类的新闻:

// 替换为实际要查询的分类ID
int targetCategoryId = 1;

var postList = _unitOfWork.GenericRepository<Posts>()
    .GetAll(
        filter: post => post.PostCategories.Any(pc => pc.CategoryId == targetCategoryId),
        include: query => query.Include(p => p.PostCategories).ThenInclude(pc => pc.Category)
    ).ToList();

3. 可选:增加已发布新闻过滤

如果只需要获取已发布的新闻,可在过滤条件中追加状态判断:

var postList = _unitOfWork.GenericRepository<Posts>()
    .GetAll(
        filter: post => post.IsPublished == Published.Yes 
                        && post.PostCategories.Any(pc => pc.CategoryId == targetCategoryId),
        include: query => query.Include(p => p.PostCategories).ThenInclude(pc => pc.Category)
    ).ToList();

4. 注意事项

  • 确认UnitOfWork已正确注入GenericRepository,且DbContext配置了实体间的正确关联(比如PostCategory的外键映射)。
  • 若使用EF Core,确保导航属性加载正常,避免因延迟加载未启用导致的空引用异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 11:22:50