【问题标题】:How can I use wildcards in EF Core Like function如何在 EF Core Like 函数中使用通配符
【发布时间】:2019-09-05 13:05:07
【问题描述】:

.NET Core 2.2.0

我想在EF Core 的 Like 函数中使用通配符,但它不能按我预期的方式工作,我在一些帖子中读到过(最好的例子 here

我的代码:

List<string> list = new List<string>();
list.Add("Hi fransois");
list.Add("Hi francois");
list.Add("Hi françois");

List<string> testa = list.Where(a => EF.Functions.Like(a, "%francois%")).ToList();      // Results in 1 hit, as expected
List<string> testb = list.Where(b => EF.Functions.Like(b, "%françois%")).ToList();      // Results in 1 hit, as expected
List<string> testc = list.Where(c => EF.Functions.Like(c, "%fran[cç]ois%")).ToList();   // Results in 0 hits, EXPECTED: 2

为什么没有按预期工作?

【问题讨论】:

  • 请提供样本数据。
  • 不,这些调用不会返回任何内容,因为它们是 only supported in LINQ to Entities queries。您正在使用 LINQ to Objects。阅读How to Ask 并创建一个minimal reproducible example,包括您的特定数据库提供程序。
  • 其实这是我的整个测试代码,放在我的 OnGet 方法(ASP.Net Core Razor 页面)中。 testa 包含“Hi francois”,而 testb 包含“Hi françois”,因此类似方法在我的列表中有效。但是当使用通配符时,它什么也不返回。
  • @stuartd 测试,不起作用。
  • @stuartd 逗号是可接受的通配符的分隔符,即%_[]^。接受的格式取决于数据库提供者。 SQL Server 应该接受[cç]

标签: c# entity-framework .net-core entity-framework-core


【解决方案1】:

不幸的是,这看起来行不通。但是有一个使用正则表达式的解决方法:

    Regex regex = new Regex("fran[cç]ois");
    List<string> testd = list.Where(d => regex.IsMatch(d)).ToList();

这行得通。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-05-24
    • 2019-01-21
    • 2019-12-17
    • 2017-03-11
    • 1970-01-01
    • 2014-06-22
    • 1970-01-01
    • 2021-08-30
    相关资源
    最近更新 更多