【问题标题】:Create an expression tree to convert a Guid or other type primitive type to a string创建表达式树以将 Guid 或其他类型的原始类型转换为字符串
【发布时间】:2015-10-01 09:00:05
【问题描述】:

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

我目前有一个project,用于构建用于字符串搜索的表达式树。我目前正在探索将非字符串属性转换为字符串以启用对原始类型的搜索,例如integerGuid 等。

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

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

System.InvalidOperationException : 'System.Int32' 和 'System.String' 类型之间没有定义强制运算符。

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

【问题讨论】:

  • 确实很相似,但不幸的是他们的解决方案与 linq to entity 不兼容
  • SqlFunctions.StringConvert,但它似乎只接受Nullable<Decimal>
  • 快速搜索显示,目前使用 Linq to 实体无法将 Guid 转换为字符串;关于integer SqlFunctions.StringConvert 应该可以解决问题。用法示例参见here。可能可以转换为 Expression 版本。

标签: c# sql linq-to-entities expression-trees


【解决方案1】:

基本的想法是 Expression.Convert 将作为与此代码类似的经典转换在 MSIL 中发出(假设您的属性类型是 int):

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

显然不支持此操作,因此您的情况也不支持。替代品:

我假设您已经有一个变量,我们称该变量为 MemberExpression 类型的“属性”(以类似表达式的方式表示您的属性)。

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) 尝试调用“Convert.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.

您可以结合使用这两种方法:对于 Convert.ToString API 已知的属性类型,您可以使用第二种方法。如果没有,您可以回退到您编写的更通用的方法。随意实施。

【讨论】:

    猜你喜欢
    • 2019-06-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-07-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多