Aks*_*Joy 4 c# expression-trees entity-framework-core ef-core-2.1
能够使用 SQL 函数创建调用表达式,如下所示
var likeMethod = typeof(DbFunctionsExtensions).GetMethod("Like", new[] { typeof(DbFunctions), typeof(string), typeof(string) });
Expression.Call(null, likeMethod, Expression.Constant(EF.Functions), searchKeyExpression, Expression.Constant($"%{filter.Value}%"));
Run Code Online (Sandbox Code Playgroud)
我只需要了解如何使用整数或十进制列等列的功能与 Like 函数一起使用。如果我使用上述表达式,则会出现以下错误。我怎样才能像使用非字符串数据类型一样使用带有 ef 的表达式
参数例外:System.Int32 表达式中的参数例外不能用于类型 System.String 的方法 Boolean Like (Ef.DBfuntions) 的参数
var likeMethod = typeof(DbFunctionsExtensions).GetMethod("Like", new[] { typeof(DbFunctions), typeof(string), typeof(string) });
Expression.Call(null, likeMethod, Expression.Constant(EF.Functions), searchKeyExpression, Expression.Constant($"%{filter.Value}%"));
Run Code Online (Sandbox Code Playgroud)
正如我所看到的,在下面的示例中,有一个选项可以在 Ef.Functions Like 方法中执行此操作
context.Set<MyEntity>().Where(e => EF.Functions.Like((string)(object)e.IntCol, "%1%"))
Run Code Online (Sandbox Code Playgroud)
但是我如何使用成员表达式来做到这一点。
来源:- https://github.com/aspnet/EntityFrameworkCore/issues/9578
这是直线查询的解决方案。 https://github.com/aspnet/EntityFrameworkCore/issues/16195
EF Core 版本:(ASP.NET Core 2.1)数据库提供程序:(例如 Microsoft.EntityFrameworkCore.SqlServer) 操作系统:IDE:(例如 Visual Studio 2017 15.4)
“双重转换”(string)(object)e.IntCol是一种欺骗 C# 编译器将int参数“传递”给需要参数的方法string(如EF.Functions.Like)的方法。当然,如果该方法被实际调用,您将在运行时得到无效的强制转换异常。
但是这个技巧是有效的,因为这样的方法永远不会被“调用”,而是被转换为 SQL,而 SqlServer EF Core 提供程序会删除此类强制转换并允许您使用 SqlServer 隐式数据转换。我在如何使用 EF Core 2.2 将 JSON_VALUE 转换为 DateTime 中使用相同的技术(尽管方向相反)?和表达式树到 SQL 与 EF Core。
这是映射到Expression方法的方式。鉴于Expression searchKeyExpression(具体Expression类型无关紧要),重要的是属性Type返回Expression.Type。如果是string,则很好,否则您需要对其应用(string)(object)强制转换,这是通过两次Expression.Convert调用实现的。
像这样的东西:
Expression matchExpression = searchKeyExpression;
if (matchExpression.Type != typeof(string))
{
matchExpression = Expression.Convert(matchExpression, typeof(object));
matchExpression = Expression.Convert(matchExpression, typeof(string));
}
var pattern = Expression.Constant($"%{filter.Value}%");
var callLike = Expression.Call(
typeof(DbFunctionsExtensions), "Like", Type.EmptyTypes,
Expression.Constant(EF.Functions), matchExpression, pattern);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4281 次 |
| 最近记录: |