本文介绍了如何在 EF Core 中匹配 PostgreSQL 列上的正则表达式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个名为 Cars 的类,它有一个名为 Index 的属性作为字符串.

I have a class called Cars with a property called Index as string.

Index 的字符串格式为 #0001,以 # 开头 &后跟 4 个数字.

The Index has a string format of #0001, which starts with # & is followed by 4 numbers.

当我将 SQL Server 与 EF 5 一起使用时,我使用以下代码获得了汽车的 Index 列表:

When I use SQL Server with EF 5, I get a list of Indexs of the car using the code below:

indexes = myContext.Cars.Where(
    c => EF.Functions.Like(c.Index, "[#][0-9][0-9][0-9][0-9]"));

现在,我已经迁移到 PostgreSQL &使用 Npgsql EF Core 库.上面的代码不再起作用.

Now, I have migrated to PostgreSQL & use Npgsql EF Core library. The code above does not work anymore.

我尝试使用下面的代码来获取匹配的Index:

I have tried using the code below to get the matching Index:

indexes = myContext.Cars
                    .Where(c => EF.Functions.ILike(mp.Index, "#%"));

上面的结果只给我任何以 # 开头的字符串,但我无法按匹配的数字数进行过滤.

The result above only gives me any string which starts with #, but I cannot filter by the matching number of digits.

我也尝试过 #[0-9]{4} 表达式,但我没有得到应有的结果.

I also have tried #[0-9]{4} expression, but I got no result when it should.

用于在 Postgres 中获得相同行为的正确表达式是什么?

What is the correct expression to use to get the same behaviour in Postgres?

谢谢

推荐答案

Npgsql EF Core provider 支持 Regex.IsMatch 的翻译,你可以替换 EF.Functions.Like使用这个静态方法:

Npgsql EF Core provider supports translation of Regex.IsMatch and you can replace EF.Functions.Like with this static method:

indexes = myContext.Cars.Where(
    c => Regex.IsMatch(c.Index, "[#][0-9][0-9][0-9][0-9]"));

完整的函数列表在这里:https://www.npgsql.org/efcore/mapping/translations.html

Full list of functions is here: https://www.npgsql.org/efcore/mapping/translations.html

这篇关于如何在 EF Core 中匹配 PostgreSQL 列上的正则表达式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-23 23:28