Reputation: 327
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?
Upvotes: 5
Views: 3054
Reputation: 8782
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) });
Upvotes: 1
Reputation: 668
Problem is that x => new {...} is already the expression you pass as an argument to Select(...). Your code will work if you compile and invoke SomeExpr into the select expression.
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) });
Upvotes: 0