【问题标题】:C# - How can I search in a IQueryable object with Where Like %C# - 如何使用 Where Like % 在 IQueryable 对象中进行搜索
【发布时间】:2016-07-29 20:46:29
【问题描述】:

我找不到像在 SQL 命令中那样使用 LIKE %some%text% 运算符搜索 IQueryable 对象的方法。

目前我这样做:

System.Data.Entity.DbSet<Shop> database_Shops = database.Shops;
string searched_shop = !String.IsNullOrEmpty(post_data["shop"]) ? post_data["shop"] : " ";

ViewBag.shops = database_Shops
                .Where(shop => shop.Name.ToUpper().Contains( searched_shop.ToUpper()))
                .Take(RESULTS_PER_PAGES * pageNumber);

但它在shop.Name 中找不到没有空格的条目。有人知道这样做的方法吗?

非常感谢!

【问题讨论】:

  • LIKE 也找不到名字中的空格,你知道的。
  • 当然是的,但是使用Like 方法我可以搜索所有有&没有空格的条目shop.Name LIKE "%%"

标签: c# sql asp.net iqueryable


【解决方案1】:

你可以在命名空间System.Data.Linq.SqlClient中使用SqlMethod

database_Shops.Where(shop => SqlMethods.Like(shop.Name, "%some%text%"));

SqlMethods.Like Method (String, String)

在 EF 上下文中,您可以在命名空间 System.Data.Objects.SqlClient.SqlFunctions 中使用 SqlFunctions

database_Shops.Where(shop => SqlFunctions.PatIndex("%some%text%", shop.Name) > 0);

SqlFunctions.PatIndex Method (String, String)

【讨论】:

  • "此方法目前仅在 LINQ to SQL 查询中受支持。"
  • 对我来说它不起作用。我有这个错误LINQ to Entities does not recognize the method 'Boolean Like(System.String, System.String) .. 有什么想法吗?
  • 您能否将您的完整请求粘贴到您的问题中?
  • 对于 EF,你应该使用 SqlFunctions.PatIndex msdn.microsoft.com/en-us/library/… 我会更新我的答案。
猜你喜欢
  • 1970-01-01
  • 2019-06-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-06
  • 2022-01-10
  • 2014-09-21
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多