4
I have the following expression:
Where(cd => cd.Modal == modal)
.Select(s => s.Volume)
.DefaultIfEmpty(0)
.Sum()
what use to make a same calculation several times within a few querys through LINQ and tried to create the following Extension method, but when executing my query it gives the following error message:
LINQ to Entities does not recognize the method 'system decimal Calculatevolume'
Method:
public static decimal CalculateVolume(this IEnumerable<MyEntity> query, Modal modal)
{
return query.Where(cd => cd.Modal == modal)
.Select(s => s.Volume)
.DefaultIfEmpty(0)
.Sum();
}
Here’s an example of how I tried to execute the command:
var modal = 1;
_context.EntityTeste
.Select(c => new
{
Current = c.MyEntity.CalculateVolume(modal)
})
The entity MyEntity
is a list within the EntityTeste
.
How can I make it so that I can transform this chunk of code that is repeated several times into an instruction that LINQ understands and executes in the database?
I believe that in such cases the best option is Dapper.
– George Wurthmann
@Georgewurthmann How Dapper could help a case like this?
– Jéf Bueno
@LINQ already had a very similar problem and not to load everything in memory to call the method we made a function in BD and made a query using the function using Dapper. But in my case it was calculations with date.
– George Wurthmann
But to make a function in the database and call in the query would not need Dapper, right? You can do with EF...
– Jéf Bueno
In EF6 this is a bit complicated and not everything works as it should work, in EF Core there has been a major breakthrough in this aspect can be done, the problem that I could not visualize which SQL you need to run, could edit your question and illustrate it better, is vague a little and the way you did it won’t understand it as an expression
Linq
.– novic