Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Expression in select in LINQ to SQL

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

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

where SomeFunc is something like this:

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

But working with LINQ to Entities, Func doesn't work, I must use Expression. And this code doesn't work:

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

where SomeExpr is something like this:

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

How can I use Expressions in Select in query?

like image 596
zampotex Avatar asked Nov 08 '22 09:11

zampotex


1 Answers

You have to compile and execute the query

var query2 = Enumerable.Range(1, 10)
                  .AsQueryable()
                  .Select(x => new { A = x, B = SomeExpr.Compile().DynamicInvoke(x) });
like image 139
PiotrWolkowski Avatar answered Nov 14 '22 23:11

PiotrWolkowski