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函数。
提前致谢
由于当前既没有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)
归档时间: |
|
查看次数: |
696 次 |
最近记录: |