Why can't I reuse a function in LINQ to SQL?

Why is the LINQ to SQL statement below throwing an exception?

I have a function

bool TrimAndCompare(string s1, string s2)
{
   return customer.CustomerID.Trim() == customerID.Trim()
}

... some other function, I call the function above in my linq statement

var customers = from customer in _context.Customers
                          where
                              TrimAndCompare(customer.CustomerID, customerID)
                      select customer;

The above statments LINQ to SQL function throws an exception but below not Why ???

var customers = from customer in _context.Customers
                      where
                            customer.CustomerID.Trim() == customerID.Trim()
                      select customer;

I get a 'System.NotSupportedException' where I try to access clients

+3
source share
1 answer

In the second fragment, the logic is translated into a lambda expression, which is then compiled into an expression tree ... two queries:

_context.Customers
        .Where(customer => TrimAndCompare(customer.CustomerID, customerID);

vs

_context.Customers
        .Where(customer => customer.CustomerID.Trim() == customerID.Trim());

LINQ to SQL , , Trim . , , .

, , , :

Expression<Func<Customer, bool>> CustomerIdMatches(string customerID)
{
   return customer => customer.CustomerID.Trim() == customerID.Trim()
}

:

from customer in context.Customers.Where(CustomerIdMatches(customerID))
... rest of query here

Where.

. , ... , .

:

var query = context.Customers
                   .Where(TrimAndCompare(customer => customer.CustomerID,
                                         customer => customerID));

: (

+8

Source: https://habr.com/ru/post/1729350/


All Articles