【问题标题】:EF Core 3.1 searching filterEF Core 3.1 搜索过滤器
【发布时间】:2020-04-29 06:58:42
【问题描述】:

我正在尝试使用很多选项(字符串输入、选择输入...)创建搜索过滤器。如果 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);
        }

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

【问题讨论】:

  • 您必须使用流畅调用的返回值才能生效。例如tags.Include(s =&gt; s.Category) -> tags = tags.Include(s =&gt; s.Category)

标签: ef-core-3.1


【解决方案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);
    }

【讨论】:

    猜你喜欢
    • 2022-02-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-29
    • 2021-10-01
    • 2022-11-28
    • 2021-04-24
    • 2021-04-21
    相关资源
    最近更新 更多