Reputation: 11190
I have a lambda expression:
(x) => x.Visits++
At runtime, I want to translate this into the string:
"set Visits = Visits + 1"
or, potentially, if the underlying data store is different (like MongoDB)
{$inc: {Visits : 1}}
I think the way to do this is to use expression trees, but when I assign the lambda expression to an expression tree, I get "An expression tree may not contain an assignment operator".
Is there any way to accomplish this short of writing a full up linq implementation that supports Update?
Upvotes: 1
Views: 1367
Reputation: 1751
There is no need in the compiler support, the expression tree can be constructed from MSIL. This project implements it - https://github.com/kostat/XLinq
Disclaimer: I'm a maintainer.
Upvotes: 0
Reputation: 1064054
That simply isn't supported by the current C# compiler, and I haven't heard about any changes in vNext. Of course, strictly speaking it isn't defined for C# 3 / 4 - there is just a "is defined elsewhere" (actually, AFAIK: the spec for handling expression tree construction still isn't formally documented; this could be a positive thing, as it is hard to argue that it will require specification changes ;p).
The funny thing is: from .NET 4.0 onwards, the expression tree API does support mutate (in this case, see Expression.Increment
and Expression.PostIncrementAssign
) - so you could create the expression tree at runtime via Expression.*
code, but frankly that is a pain and hard to manage. So there is potential for this to change, but don't be too hopeful.
Also keep in mind - the expression tree analysis to pull it back out again is far from trivial. Doable, sure; easy: no.
Upvotes: 4