我正在使用Net Core项目,使用实体框架,mysql数据库和pomelo框架。我需要执行此查询,以便比较模型中属性的最后X个字符与模式:
_context.Cars
.Where(c => EF.Functions.Like(c.CarName.ToString().Right(5), pattern))
.ToList();
我想知道Entity框架Core中是否有任何SQL RIGHT函数等效。
提前致谢
由于目前既没有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();