我正在使用一个netcore项目,使用实体框架、mysql数据库和pomelo框架。我需要执行此查询,以便将模型中属性的最后x个字符与模式进行比较:
_context.Cars .Where(c => EF.Functions.Like(c.CarName.ToString().Right(5), pattern)) .ToList();
我想知道实体框架核心中是否有任何sql right函数等效。提前谢谢
gcmastyq1#
因为目前没有clr string 也不是 EF.Functions 调用的方法 Right ,答案是ef-core目前没有提供sql的等价物 RIGHT 功能。幸运的是,efcore允许您使用efcore2.0引入的数据库标量函数Map添加它。例如,添加以下类:
string
EF.Functions
Right
RIGHT
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 覆盖:
Register
OnModelCreating
protected override void OnModelCreating(ModelBuilder modelBuilder) { // ... MyDbFunctions.Register(modelBuilder); // ... }
你就完了。现在您应该能够使用所需的:
5us2dqdw2#
使用以下选项:
_context.Cars.Where(w => DbFunctions.Right(w.CarName,5)==pattern).ToList();
2条答案
按热度按时间gcmastyq1#
因为目前没有clr
string
也不是EF.Functions
调用的方法Right
,答案是ef-core目前没有提供sql的等价物RIGHT
功能。幸运的是,efcore允许您使用efcore2.0引入的数据库标量函数Map添加它。
例如,添加以下类:
(稍后,如果需要,您可以添加更多这样的函数)。
然后将呼叫添加到
Register
从你的背景来看OnModelCreating
覆盖:你就完了。现在您应该能够使用所需的:
5us2dqdw2#
使用以下选项: