Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I call local method in Linq to Entities query?

I have the following code:

public void SalesCount(string customerId)
{
  ..
  ..
  return ...;
}

var resultQuery = dataContext.Customers
.Where (c => c.Name == "Alugili")
.Where (c => SalesCount(c.CustomerId) < 100);

When I execute resultQuery I get a translation to SQL exception.

I need to call SalesCount in the Where can I do that is there any workaround for this problem!

like image 455
Bassam Alugili Avatar asked Sep 10 '13 09:09

Bassam Alugili


People also ask

How do I call a method inside a LINQ query?

var q = (from a in v.A join b in v.B on a.i equals b.j where a.k == "aaa" && a.h == 0 select new {T = a.i, S = someMethod(a.z). ToString()}) return q; The line S = someMethod(a.z).

Can we use LINQ with Entity Framework?

To execute a LINQ to Entities query against the Entity Framework, the LINQ query must be converted to a command tree representation that can be executed against the Entity Framework.

How do you call a function in Entity Framework?

Step 1: Create an entity class which inherits “DbContext” class. Step 2: The following is the structure of the database with table and stored procedure. Step 3: Create a class to store the returned tabular value. Step 4: Create an object for the entity above and method to call a function.

How LINQ queries converted into SQL queries?

LINQ to SQL translates the queries you write into equivalent SQL queries and sends them to the server for processing. More specifically, your application uses the LINQ to SQL API to request query execution. The LINQ to SQL provider then transforms the query into SQL text and delegates execution to the ADO provider.


2 Answers

Simply you can't. You can't execute C# code on the SQL server directly, you can use only Expressions and some special recognized functions...

Unless you transform your query (at least partially) in a LINQ-to-Objects...

var resultQuery = dataContext.Customers
    .Where (c => c.Name == "Alugili")
    .AsEnumerable()
    .Where (c => SalesCount(c.CustomerId) < 100);

Be aware that the last Where will be executed on the client side, so many useless rows will be fetched from the DB.

like image 65
xanatos Avatar answered Nov 03 '22 23:11

xanatos


Try

var resultQuery = dataContext.Customers
.Where (c => c.Name == "Alugili")
.ToArray()
.Where (c => SalesCount(c.CustomerId) < 100);

But then the second Where is not run as SQL but locally - all customers with the name "Alugili" are pulled from the DB...

Otherwise you have to write out your method directly in the where method as lambda expression.

like image 30
Rico Suter Avatar answered Nov 03 '22 22:11

Rico Suter