首页 > 解决方案 > EF Core 3.1 搜索过滤器

问题描述

我正在尝试使用很多选项(字符串输入、选择输入...)创建搜索过滤器。如果 categoryId 大于 0,我需要按类别过滤标签,如果 categoryId 等于 0,则返回所有相关类别的所有标签(或不应用类别选项进行搜索)。但是我的代码在这两种情况下都没有返回任何类别,也没有给我任何错误。我在互联网上找到的很多示例都显示了一个字符串输入是如何工作的。

        IQueryable<Tag> tags = _context.Tag
                                .Where(s => EF.Functions.Like(s.Name, "%" + name + "%"))
                                .Where(s => EF.Functions.Like(s.Description, "%" + description + "%"))
                                .Include(s => s.Value)
                                .Include(s => s.Period);     
        if (categoryId > 0)
        {
            tags.Include(s => s.Category).Where(s => s.Category.CategoryId == categoryId);
        }
        else
        {
            tags.Include(s => s.Category);
        }

谁能解释为什么我的代码不起作用?以及如何实现这个功能?谢谢。

标签: ef-core-3.1

解决方案


正确的代码是:

IQueryable<Tag> tags = _context.Tag
                            .Where(s => EF.Functions.Like(s.Name, "%" + name + "%"))
                            .Where(s => EF.Functions.Like(s.Description, "%" + description + "%"))
                            .Include(s => s.Value)
                            .Include(s => s.Period);     
    if (categoryId > 0)
    {
        tags = tags.Include(s => s.Category).Where(s => s.Category.CategoryId == categoryId);
    }
    else
    {
        tags = tags.Include(s => s.Category);
    }

推荐阅读