我正在处理一个 Net Core 项目,使用 Entity Framework 、mysql 数据库和 pomelo 框架。我需要执行此查询,以便将模型中属性的最后 X 个字符与模式进行比较:
_context.Cars
.Where(c => EF.Functions.Like(c.CarName.ToString().Right(5), pattern))
.ToList();
我想知道 Entity Framework Core 中是否有等效的 SQL RIGHT 函数。
提前致谢
最佳答案
更新(EF Core 5.0+):
EF Core 5.0 在 DbFunctionAttribute
和 IsBuiltIn(bool)
流畅的 API 上引入了 IsBuiltIn
属性,因此不再需要提供翻译。最小映射与 EF Core 2.x 中的相同,只是
[DbFunction("RIGHT", "")]
替换为
[DbFunction("RIGHT", IsBuiltIn = true, IsNullable = true)]
EF Core 5 还允许 Configuring nullability of user-defined function based on its arguments , 但它只能流利地完成,因此您可以考虑使用显式映射而不是通用代码。例如
public static class MyDbFunctions
{
public static string Right(this string s, int length)
=> throw new InvalidOperationException();
public static void Register(ModelBuilder modelBuider)
{
var fb = modelBuilder.HasDbFunction(() => Right(default, default))
.HasName("RIGHT").IsBuiltIn(true).IsNullable(true);
fb.HasParameter("s").PropagatesNullability(true);
}
}
更新(EF Core 3.0+):
从 Ef Core 3.0 开始,空字符串架构被视为与 null
相同,即将默认架构添加到函数名称之前。这样,如果您想添加内置功能,则必须提供“翻译”(奇怪的决定)。
所以你需要添加
using Microsoft.EntityFrameworkCore.Query.SqlExpressions;
并修改代码如下
modelBuider.HasDbFunction(dbFunc).HasTranslation(args =>
SqlFunctionExpression.Create(dbFunc.Name, args, dbFunc.ReturnType, null));
原文:
由于目前既没有 CLR string
也没有 EF.Functions
方法调用 Right
,答案是 EF Core 目前没有提供等效的方法SQL RIGHT
函数。
幸运的是,EF Core 允许您使用引入的 EF Core 2.0 添加它 Database scalar function mapping .
例如,添加以下类:
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);
}
}
}
(稍后您可以根据需要添加更多类似的功能)。
然后从您的上下文 OnModelCreating
覆盖中添加对 Register
的调用:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// ...
MyDbFunctions.Register(modelBuilder);
// ...
}
你就完成了。现在您应该能够使用所需的:
_context.Cars
.Where(c => EF.Functions.Like(c.CarName.ToString().Right(5), pattern))
.ToList();
关于c# - Entity Framework Core 中等效的 SQL RIGHT 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52213298/