C# expression tree for ordinary code

Posted by rwallace on Stack Overflow See other posts from Stack Overflow or by rwallace
Published on 2010-05-12T07:27:50Z Indexed on 2010/05/12 7:54 UTC
Read the original article Hit count: 213

It's possible to create an expression tree, if you declare it as such.

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

What I'm trying to do is, let's say for an order processing system, I have a class for order items:

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 net value equals qty * price, so I'd like to declare it as such, either with a property or method, and then also have the framework introspect that expression so it can generate appropriate SQL for defining a corresponding calculated column in a corresponding database view.

The most obvious way to do this would be to get the expression tree for a property getter or a method, but I can't find any indication how to do this, or that it is possible. (I have found a way to get a method body as a byte stream, but that's not what's desired here.)

If that isn't possible, I suppose the recommended solution would be to declare something like a static field that is an expression tree, and compile/run it at run time for internal use, and also introspect as normal for SQL generation?

© Stack Overflow or respective owner

Related posts about c#

Related posts about .NET