Search code examples
c#entity-frameworklinqexpression-trees

Linq to entities Expression parse string to int


I have an issue with this code used in a 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 is an object that set properties for other objects (Book) the value of the property is store in a "value" field in database. Because value can store booleans, integers, doubles, text etc. it's set to string.

In this particular case I need to parse the string to int.

It doesn't work, I think, because some value fields store non parseable values.

And I get thise error:

FormatException: Input string was not in a correct format.

But I don't know how to deal with it.

Thanks for your Help.


Solution

  • Finaly I found the solution it was just a matter of operator:

    The goal of the expression was to obtain a linq query like this:

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

    For that I used Expression.And() operator. That was the mistake: && correspond ton AndAlso operator