实体框架核心中的SQL RIGHT函数等效项

Jaw*_*wen 2 c# mysql entity-framework-core .net-core

我正在使用实体框架,mysql数据库和pomelo框架进行Net Core项目。我需要执行此查询,以便将我模型中属性的最后X个字符与一个模式进行比较:

_context.Cars
.Where(c => EF.Functions.Like(c.CarName.ToString().Right(5), pattern))
.ToList();
Run Code Online (Sandbox Code Playgroud)

我想知道实体框架核心中是否有等效的SQL RIGHT函数。

提前致谢

Iva*_*oev 7

由于当前既没有CLR string也没有EF.Functions方法被调用Right,答案是EF Core当前不提供等效的SQL RIGHT函数。

幸运的是,EF Core允许您使用EF Core 2.0引入的数据库标量函数映射进行添加

例如,添加以下类:

using System;
using System.Linq;

namespace Microsoft.EntityFrameworkCore
{
    public static class MyDbFunctions
    {
        [DbFunction("RIGHT", "")]
        public static string Right(this string source, int length)
        {
            if (length < 0) throw new ArgumentOutOfRangeException(nameof(length));
            if (source == null) return null;
            if (length >= source.Length) return source;
            return source.Substring(source.Length - length, length);
        }

        public static void Register(ModelBuilder modelBuider)
        {
            foreach (var dbFunc in typeof(MyDbFunctions).GetMethods().Where(m => Attribute.IsDefined(m, typeof(DbFunctionAttribute))))
                modelBuider.HasDbFunction(dbFunc);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

(以后可以根据需要添加更多类似功能)。

然后Register在您的上下文OnModelCreating覆盖中添加呼叫:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    // ...
    MyDbFunctions.Register(modelBuilder);
    // ...
}
Run Code Online (Sandbox Code Playgroud)

您完成了。现在您应该可以使用所需的了:

_context.Cars
.Where(c => EF.Functions.Like(c.CarName.ToString().Right(5), pattern))
.ToList();
Run Code Online (Sandbox Code Playgroud)

  • @IvanStoev 使用此代码修复: modelBuilder .HasDbFunction(typeof(CustomDbFunctions).GetMethod(nameof(Right))!) .HasSchema(null) .HasTranslation(args =&gt; SqlFunctionExpression.Create("RIGHT", args, typeof(string) , 无效的)); (2认同)