EF + LINQ: How do I define and utilize a variable (maybe a Func variable) to define part of a Select statement?

Viewed 1599

Before try to use a variable (this has sql server do the calculation):

IQueryable<MyEntity> query = _dbSet; // IQueryable<TEntity>
var results = query.Select(m => new MyViewModel
{
    MyCalculation = m.Column1 * m.Column2
}).ToList();

What I want to do (dynamically create part of my select statement from a Func variable or some other kind of variable to allow this):

IQueryable<MyEntity> query = _dbSet; // IQueryable<TEntity>
Func<MyEntity, decimal> funcVariableAttempt = m => m.Column1 * m.Column2;
var results = query.Select(m => new MyViewModel
{
    MyCalculation = funcVariableAttempt.Invoke(m) // My foolish attempt does not work.
}).ToList();

The error I get when I try what I want (aka my foolish attempt):

LINQ to Entities does not recognize the method 'System.Decimal Invoke(MyProject.Repository.Models.MyEntity)' method, and this method cannot be translated into a store expression.

How do I define and utilize a variable (maybe a Func variable) to define part of a Select statement?

3 Answers
Related