Linq to entities Expression将字符串解析为int

时间:2017-07-09 21:59:57

标签: c# entity-framework linq expression-trees

我在linq to entities Expression中使用此代码时遇到问题:

int _val = Convert.ToInt32(value);
Expression term1 = Expression.Equal(Expression.Property(Expression.PropertyOrField(bookProperty, "type"), "key"), Expression.Constant("taille", typeof(string)));
Expression temp1 = Expression.Property(bookProperty, "value");
MethodInfo Parse = typeof(int).GetMethod("Parse", new[] { typeof(string) });
Expression term2 = Expression.GreaterThanOrEqual(Expression.Call(Parse, temp1), Expression.Constant(_val, typeof(int)));
conditions = Expression.And(term1, term2);

bookproperty是一个为其他对象设置属性的对象(Book) 属性的值存储在数据库的“值”字段中。 因为值可以存储布尔值,整数,双精度,文本等,所以它设置为字符串。

在这种特殊情况下,我需要将字符串解析为int。

我认为它不起作用,因为某些值字段存储了不可解析的值。

我得到了这个错误:

  

FormatException:输入字符串的格式不正确。

但我不知道如何处理它。

感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

最后我发现解决方案只是运营商的问题:

表达式的目标是获得这样的linq查询:

bookProperty.Where(b=> b.type== "taille && b.value == 1)

为此,我使用了Expression.And()运算符。 这是错误:&&对应吨AndAlso运算符

答案 1 :(得分:0)

我认为如果值不是int那么你应该停止操作。您可以使用int.TryParse方法

        if (!int.TryParse(bookProperty, out bookProperty))
        {
            // break the operation. You can also have error handling code here.
            return;
        }