Question

I have a simple LINQ-to-Entities query as below:

 var BillingNumbers = from o in dbcontext.Orders
                      where SqlFunctions.IsNumeric(o.BillingNumber) == 1
                      select o.BillingNumber;

This query works most of the time. Recently, however, I encountered a situation where the BillingNumber was indeed numeric, but had some trailing spaces. This query completely missed those values.

If SqlFunctions.IsNumeric() can't ignore the trailing spaces, what are the alternatives?

.Net 4/EF4/VS2010

Was it helpful?

Solution

You can do

where SqlFunctions.IsNumeric(o.BillingNumber.Trim()) == 1

It translates to

WHERE (ISNUMERIC(LTRIM(RTRIM([Extent1].[BillingNumber])))) > 0

Be aware of the fact that this way of querying is not sargable, so if you can narrow down your orders in any other way before this comparison, make sure you do it!

OTHER TIPS

Although I don't like the idea of storing numbers in strings, since you are only looking for 6-digit strings, you can do something like this:

SqlFunctions.PatIndex("%[0-9][0-9][0-9][0-9][0-9][0-9]%", o.BillingNumber) > 0

Although it would give you false positives for numbers with things other than spaces, but you can adjust for that.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top