0

I'm trying to change on which field the Where clause will be applied depending on a Boolean value received by the function. So far I have this:

Public Function SomeFunction(ByVal value As String, Optional bValueIsString As Boolean = False) As JsonResult
    ...
    Dim q = (From t In table
                 Where If(bValueIsString, t.Desc=value, t.Id=value)
                 Select New With {.Id,
                                  .LongDescription,
                                  .Desc)})
    ...
End Function

But I keep receiving:

Conversion from string "someString" to type 'Integer' is not valid.

.. when I set bValueIsString to true.

-

I know about ScottGu's Dynamic LINQ Library, but I would rather not use any external component if possible..

4

1 回答 1

1

This is because operands two and three to the IF function must have the same type, or be implicitly convertible, so that they may be automatically converted. In this case, the operands are being converted to integers, and value doesn't contain a valid value for the conversion. Changing your code to explicitly compare strings should fix the issue:

If(bValueIsString, t.Desc=value, t.Id.ToString()=value)

See the comments on this answer for further reading.

于 2013-04-23T14:24:22.150 回答