c# - 尝试评估 LINQ 查询参数表达式时引发异常
问题描述
我在标题中有错误。可能我必须控制 string.IsNullOrEmpty(searchString) 但我没有。我的代码如下。请帮助我
谢谢大家我解决了这个问题。问题不在这里。我的路线代码有问题。因为搜索不同,我会写我的路线代码
endpoints.MapControllerRoute(
name:"search",
pattern: "{search}",
defaults: new {controller="Shop",action="search"}
);
但不是 from of 模式:“{search} 应该是这个模式:”search” 感谢所有帮助过的人
public List<Product> GetSearchResult(string searchString)
{
using (var context = new ShopContext())
{
var products = context
.Products
.Where(i=> i.IsApproved && (i.Name.ToLower().Contains(searchString.ToLower()) || i.Description.ToLower().Contains(searchString.ToLower())))
.AsQueryable();
return products.ToList();
}
}
解决方案
我将其分解如下:
public List<Product> GetSearchResult(string searchString)
{
// What do you want to do if searchString is null or blank? (Pick one:)
// You could send back an empty result...
if (String.IsNullOrWhiteSpace(searchString))
return null;
// Or you could convert it to a blank string
if (searchString == null)
searchString = "";
List<Product> products = new List<Product>();
using (var context = new ShopContext())
{
products = context.Products.ToList();
}
// Always check for null and empty after going to the DB
if (products == null || products.count = 0)
return null;
// If we are still here, then we can finally do the search
List<Product> results = products.Where(i=> i.IsApproved &&
(i.Name != null && i.Name.ToLower().Contains(searchString.ToLower()) ||
(i.Description != null && i.Description.ToLower().Contains(searchString.ToLower())));
return results;
}
注意:我没有对此进行测试,并且在最后一个带有 ('s 和 )'s 的 LINQ 语句中可能存在语法错误。
编辑:
上面的示例将拉回Product
表中的所有记录,然后在内存中过滤结果。如果您想避免这种情况,那么我认为这应该可行:
public List<Product> GetSearchResult(string searchString)
{
// What do you want to do if searchString is null or blank? (Pick one:)
// You could send back an empty result...
if (String.IsNullOrWhiteSpace(searchString))
return null;
// Or you could convert it to a blank string
if (searchString == null)
searchString = "";
using (var context = new ShopContext())
{
List<Product> products = context.Products.Where(i=> i.IsApproved &&
(i.Name != null && i.Name.ToLower().Contains(searchString.ToLower()) ||
(i.Description != null && i.Description.ToLower().Contains(searchString.ToLower()))).ToList();
return products;
}
}
这与您的 OP 之间的主要区别在于,我们正在检查是否为空,Name
并且Description
我相信这样做的方式是 EF 可以将其转换为查询。
推荐阅读
- ios - 使用 1080p 复制 CVPixelBufferRef 时 memcpy 崩溃
- nlp - NLP、spaCy:提高文档相似度的策略
- javascript - 无法从内容脚本与 Chrome 扩展程序中的弹出窗口进行通信
- css - 带有 css 参考的 Kendo UI 网格
- vue.js - Vuejs选择框在加载时选择了项目
- selenium - 无法通过我的 selinium 测试套件单击“继续执行第 3 步”(尝试使用 id、className 和 xpath)
- python - 围绕字符串某些部分的python单引号
- odoo-8 - 字段更改时产品添加到行
- angular - Angular 6 - 从工作区嵌入应用程序
- office365 - 通过图形API直接在office365中离线打开单盘文档