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

Blazor中如何将单列SQL搜索扩展为多列过滤功能?

实现Blazor多列搜索功能

要扩展单列搜索到多列过滤,只需在LINQ的Where条件中用**逻辑或(||)**组合多个字段的匹配规则即可,同时可以优化搜索的大小写敏感性和空值处理。

修改后的多列搜索代码

假设你的RequestList实体还有RequestId、Description、CreatedBy等需要搜索的字段,调整后的方法如下:

public async Task<List<RequestList>> SearchRequestAsync(string searchItem)
{
    // 搜索词为空时返回全部数据
    if (string.IsNullOrWhiteSpace(searchItem))
    {
        return await context.RequestLists.ToListAsync();
    }

    // 统一转为小写,避免大小写敏感问题
    var lowerSearchText = searchItem.ToLower();

    return await context.RequestLists
        .Where(s => 
            // 匹配RequestName
            s.RequestName.ToString().ToLower().Contains(lowerSearchText)
            // 匹配RequestId(如果是数字类型,转字符串后再匹配)
            || s.RequestId.ToString().ToLower().Contains(lowerSearchText)
            // 匹配Description,先判断非空避免空引用异常
            || (s.Description != null && s.Description.ToLower().Contains(lowerSearchText))
            // 匹配CreatedBy
            || (s.CreatedBy != null && s.CreatedBy.ToLower().Contains(lowerSearchText))
        )
        .ToListAsync();
}

关键优化点

  • 多字段组合:用||连接多个字段的Contains判断,只要任意一个字段包含搜索词,该条数据就会被筛选出来
  • 大小写不敏感:将搜索词和字段值统一转为小写,避免因大小写差异导致的漏查
  • 空值处理:对可能为null的字段(如Description)先做非空判断,防止运行时抛出空引用异常
  • 空搜索兼容:当用户未输入搜索词时,返回全部数据,提升交互体验

Blazor组件中使用示例

在Razor组件里绑定搜索输入并调用该方法:

<!-- 搜索输入框,实时绑定搜索词 -->
<input 
    type="text" 
    @bind="@searchTerm" 
    @bind:event="oninput" 
    placeholder="搜索请求名称、ID、描述..." 
    class="form-control"
/>

<!-- 展示搜索结果 -->
@if (requestResults != null)
{
    <div class="mt-3">
        @foreach (var request in requestResults)
        {
            <div class="card mb-2">
                <div class="card-body">
                    <h5>@request.RequestName</h5>
                    <p>ID: @request.RequestId</p>
                    <p>@request.Description</p>
                </div>
            </div>
        }
    </div>
}

@code {
    private string searchTerm = string.Empty;
    private List<RequestList>? requestResults;
    
    // 注入你的数据服务
    [Inject] private IRequestService RequestService { get; set; } = default!;

    protected override async Task OnInitializedAsync()
    {
        // 初始化加载全部数据
        requestResults = await RequestService.SearchRequestAsync(searchTerm);
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.19 00:37:42