Expression in select in LINQ to SQL

If I work with LINQ to Objects, I can use Func<TIn, TOut>in Select, for example:

Enumerable.Range(1, 10).Select(x => new { A = x, B = SomeFunc });

where SomeFuncit looks something like this:

Func<int, long> SomeFunc = x => x * x;

But working with LINQ to Entities, Func does not work, I have to use Expression. And this code does not work:

var query = Enumerable.Range(1, 10)
                   .AsQueryable()
                   .Select(x => new { A = x, B = SomeExpr });

where SomeExprit looks something like this:

Expression<Func<int, long>> SomeExpr = x => x * x;

How to use expressions in Select in a query?

+4
source share
3 answers

You must compile and execute the query

var query2 = Enumerable.Range(1, 10)
                  .AsQueryable()
                  .Select(x => new { A = x, B = SomeExpr.Compile().DynamicInvoke(x) });
+1
source

The problem is that x => new {...} is already an expression that you pass as an argument to Select (...). Your code will work if you compile and call SomeExpr in the select statement.

Expression<Func<int, long>> SomeExpr = x => x * x;

var query = Enumerable.Range(1, 10)
                      .AsQueryable()
                      .Select(x => new { A = x, B = SomeExpr.Compile().Invoke(x) });
0

B Expression type, :

x => new { A = x, B = SomeExpr };

x => new { A = x, B = Expression.Multiply(Expression.Constant(x, typeof(int)),Expression.Constant(x, typeof(int)))};
0

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


All Articles