首页 > 解决方案 > 尝试评估 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();
            }
        }

标签: c#.netasp.net-mvcasp.net-coreasp.net-web-api

解决方案


我将其分解如下:

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 可以将其转换为查询。


推荐阅读