Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to check numeric value in linq to entities

I’m trying to translate the following SQL-Select to LINQ to Entities and have a problem with an isnumeric check and hope that the community can give me a hint how to resolve it.

select top(1) column1
from myDataTable with (nolock)
where id = '123456789'
and ISNUMERIC(column1) = 0

The tipping point is column1 which is from type varchar and can contain either alphanumeric values as well as numeric values.

I tried the following in LINQ to Entities to get the whole row from the table:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

int column1Value;
int paramId = 123456789;
var entry = myDataTable.FirstOrDefault(
x => x.Id == paramId && !(int.TryParse(x.column1, out column1Value))
);

In the next step I wanted to check entry for null and then get the value from column1.

But when I debug it, I get the following error

LINQ to Entities does not recognize the method ‘Boolean TryParse(System.String, Int32 ByRef)’.

How can I implement the isnumeric check in LINQ?

>Solution :

var value1 = (from d in myDataTable 
        where d.id == "123456789"
        && SqlFunction.IsNumeric(d.column1) == 0
        select d.Column1).FirstOrDefault();

IsNumeric and, in fact, all of SqlFunction exist merely to tell Linq to use the same-named function in SQL. It’s defined like this:

[System.Data.Objects.DataClasses.EdmFunction("SqlServer", "ISNUMERIC")]
public static int? IsNumeric (string arg);

SqlFunctions defines many other SQL functions you can use, including CurrentUser, DataLength, IsDate and Checksum.

You can use the EdmFunctionAttribute on C# methods allow using your user-defined SQL function in LINQ statements.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading