Query providers, like mongoDB query provider, use expression trees instead of delegates. That's why you have to declare your variable as
Expression<Func<ApiStatisticsAggregatedStats, string>> idFunc = x => x.Api
You can still assign a lambda expression to Expression<Func<...>>
variable, because compiler can transform your lambda into proper method calls from Expression
class during compilation.
When a lambda expression is assigned to a variable of type
Expression<TDelegate>
, the compiler emits code to build an expression tree that represents the lambda expression.
However, it works for single-line lambdas only.
The C# and Visual Basic compilers can generate expression trees only from expression lambdas (or single-line lambdas). It cannot parse statement lambdas (or multi-line lambdas).
If you'd try doing following:
Expression<Func<ApiStatisticsAggregatedStats, string>> idFunc = x => { return x.Api };
(notice {
and }
) you'd get compile error saying compiler is not able to transform multi-line lambda into expression tree.
Bot quotes come from Expression Trees (C# and Visual Basic).