Expression tree for regular code

You can create an expression tree if you declare it as such.

But is it possible to get an expression tree for a regular piece of code, such as a method or getter property?

What I'm trying to do, say, for an order processing system, I have a class for order elements:

class Item : Entity { [Cascade] public Document document { get; set; } public int line { get; set; } public Product product { get; set; } public string description { get; set; } public decimal qty { get; set; } public decimal price { get; set; } public decimal net { get { return qty * price; } } public VatCode vat_code { get; set; } } 

where the network value is qty * price, so I would like to declare it as such, either using a property or method, and then also have a structure that parses this expression so that it can generate the appropriate SQL to determine the corresponding calculated column in the corresponding base view data.

The most obvious way to do this is to get an expression tree for the getter property or method, but I cannot find any directions on how to do this or what is possible. (I found a way to get the body of the method as a stream of bytes, but this is not what is needed here.)

If this is not possible, I suggest that the recommended solution would be to declare something like a static field, which is an expression tree, and compile / run it at run time for internal use, and also inherit as usual for SQL generation

+4
source share
2 answers

No, not possible - a normal code is a bytecode, there is no mechanism to turn this into an expression tree. What you can do is use reflection - but that is basically it.

+1
source

I searched for a similar thing before, and I did not find the perfect way to do this, tbh.

Another problem that you are facing is that even if you have an expression tree that you want to insert in your linq query, it’s not as simple and as simple as it seems ...

For what it's worth, one way to do this is to save a static expression that will get your "network", and let the receiver of the "net" property run this expression against this .

How to add an expression to a regular linq query? I wrote a blog post about this. Basically, I create an expression expander that updates the L2S expression tree with a special expression :) Extending LINQ selectors with custom expressions

+1
source

Source: https://habr.com/ru/post/1309520/


All Articles