I’m having problems with the following Linq query (demandNb is a filter option, as a string):
Return (From auto In entity.DEMDT_AUTMT _
Where (String.IsNullOrEmpty(demandNb) OrElse auto.DEMND_NB = demandNb) _
Order By auto.NO_DEMND Descending _
Select auto).ToList()
My goal is to get all demands for the database if the filter fields is empty. If there is a filter, the function should return all demands that match the filter.
Currently, when I try to convert the IQueryable collection to a list using .ToList(), the following error is thrown:
Conversion from string "" to type 'Double' is not valid.
The problem is, when demandNb is equal to “”, this instruction auto.DEMND_NB = demandNb is still executed, throwing a conversion error.
When I remove the part after OrElse, everything works fine (although this is not the behavior I want, I want the filter to work afterall!). I have also tried to put the result in a variable (which works), and then convert it to a list, and the error is only thrown when .ToList() is called. Wierd…
Is there something I am not seeing, and why is not OrElse working as intended?
Edit:
I will be implementing several more filter fields like this (like demand owner, demand date, etc), so I cannot verify the if the filter is empty before executing the query
If I had to guess, I’d say
auto.DEMND_NBis of typeDouble, anddemandNbis obviously astring. This has nothing to do with theOrElse: you’re just trying to compare two values of non-compatible types.Since the value of
demandNbis not tied to each row in the data, I’d suggest doing something like this (pardon the C#):