简体   繁体   中英

Creating expression trees from lambda

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM