创建表达式树以将Guid或其他类型原语类型转换为字符串

本文关键字:原语 类型 类型转换 字符串 其他 表达式 Guid 创建 | 更新日期: 2023-09-27 18:15:21

当使用Linq to Entities时,结果查询应该在sql server上运行(而不是将其枚举到内存中然后执行转换)

我目前有一个项目,其中我建立表达式树的字符串搜索。我目前正在探索将非字符串属性转换为字符串的可能性,以启用对基本类型(如integerGuid等)的搜索。

我目前尝试Convert提供的lamda属性到字符串,然后使用以下命令将其交换到表达式树中:

var stringProperty = Expression.Convert(property.Body, typeof (string));

系统。InvalidOperationException:类型System之间没有定义强制操作符。Int32'和'System.String'.

我是想实现不可能的,还是有办法将扩展linq到实体以支持转换?

创建表达式树以将Guid或其他类型原语类型转换为字符串

基本思想是表达式。Convert将在MSIL中作为类似于以下代码的经典转换(假设您的属性类型是int)发出:

int value = 80;
string result = (string)value;

这个操作显然是不支持的,所以在您的情况下都不支持。替代品:

我假设你已经有了一个变量,让我们称这个变量为MemberExpression类型的"property"(以类似表达式的方式表示你的属性)。

1)尝试创建一个特殊的静态方法转换器(一个通用转换器):
public class UniversalConvertor {
     public static string Convert (object o) {
       return ... some convert logic ... :)
     }
} 
...
MethodInfo minfo = typeof (UniversalConvertor).GetMethod ("Convert", BindingFlags.Static | BindingFlags.Public);
var stringProperty = Expression.Call (null, minfo, property);

2)尝试调用"转换"。ToString"API:

MethodInfo minfo = typeof(Convert).GetMethod("ToString", BindingFlags.Static | BindingFlags.Public, Type.DefaultBinder, new Type[] { property.Type }, null);
var stringProperty = Expression.Call (null, minfo, property); // here we are calling the coresponding "Convert" method for the actually property type.

您可以结合使用这两种方法:ToString API,你可以使用第二个方法。如果没有,您可以使用自己编写的更通用的方法。请随意实现。