Ikram Khan
Ikram Khan

Reputation: 89

Calling functions in a LINQ query

My question is that how to call a function in LINQ query? e.g

source.Where(x=> double.Parse(x.Col1)==3)

or

source.Where(x=> AnyUserFunction(x.Col1)==true)

Basically my requirement is to check weather Col1 is a numeric value or not, but I occasionally need to call my User Defined functions as well.

Upvotes: 1

Views: 2132

Answers (2)

ocuenca
ocuenca

Reputation: 39376

The problem is that your Linq to Entities provider doesn't know how to translate your custom methods to SQL. The solution proposed by @teovankot is the easy way to solve this problem, but if you want to work with Linq to Objects I suggest you use AsEnumerable extension method instead ToList because AsEnumerable does not execute the query until you consult the data, it preserves deferred execution, but be careful, try to don't use AsEnumerable or ToList on the entire DbSet because you'd retrieve all rows of that table affecting your application's performance.

Now if you only want to check weather Col1 is a numeric value or not, another solution could be using SqlFunctions.IsNumeric method which is translated into native SQL:

using System.Data.Entity.SqlServer;
//...

source.Where(x=> SqlFunctions.IsNumeric(x.Col1)==1);

You can find another set of functions you can also call in the DbFunctions static class.SqlFunctions are SQL Server specific, whereas DbFunctions aren't.

Upvotes: 3

teo van kot
teo van kot

Reputation: 12491

You can't call user defined functions easy in linq to sql.

But you can do it after you get all your data from DB to your server. Like this:

 source.ToList().Where(x=> AnyUserFunction(x.Col1)==true)

Note ToList() call. this will get all your data from DB so you basically working with linq to objects where you can easy use your user defined fucntions.

Upvotes: 1

Related Questions