SQL RIGHT函数等效于Entity框架Core

问题描述 投票:2回答:1

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

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

我想知道Entity框架Core中是否有任何SQL RIGHT函数等效。

提前致谢

c# mysql .net-core entity-framework-core
1个回答
5
投票

由于目前既没有CLR string也没有EF.Functions方法称为Right,答案是EF Core目前没有提供相当于SQL RIGHT的功能。

幸运的是,EF Core允许您使用引入的Database scalar function mapping 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);
        }
    }
}

(稍后你可以根据需要添加更多这样的功能)。

然后从你的上下文Register覆盖中添加对OnModelCreating的调用:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    // ...
    MyDbFunctions.Register(modelBuilder);
    // ...
}

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

_context.Cars
.Where(c => EF.Functions.Like(c.CarName.ToString().Right(5), pattern))
.ToList();
© www.soinside.com 2019 - 2024. All rights reserved.