I have a Name
column in the table which I have coded this column with my method, now I want to execute OrderBy
on this column with EF, but before that this column needs to be decoded, the problem is it gives below error . On the other hand, if I use OrderBy
after ToList, the data retrieval speed will decrease. Is there a way to use the Extension Method on the Name column before using the ToList?
That is, as follows:
CONTEXT.TableName.OrderBy(t => t.Name.Decode()).ToList();
Error Text:
An expression tree may not contain a call or invocation that uses optional arguments
There are 2 problems.
The first one is that your Decode() method has an optional parameters. Something like:
public static string Decode(this string name, int lenght = 3)
{
// your code here
}
And that's not possible as the message explains. You can fix it by passing the optional parameter. So:
context.TableName.OrderBy(t => t.Name.Decode(default)).ToList();
But the second problem will occour. In fact you're trying to use a "custom" method that can't be translated into SQL by Linq. There's no a SQL command corresponding to the Decode method.
If you use OrderBy after ToList the speed don't decrease. Data is retrived on ToList method, so using OrderBy after ToList means ordering data client side (in C# not in SQL). If any, put Where conditions before ToList().
As the last option you can save the "decoded name" as an additional column in your table.
Hope it helps.