views:

196

answers:

2

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?

+1  A: 

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

TomTom
+1  A: 

I've been looking for a similar thing before, and I haven't found a perfect way to do this, tbh.

The other problem that you might run into, is that even if you will have an expression tree that you'd want to inject in a linq query - it's not straightforward and as easy as it sounds...

For what it's worth, one way to do this is have a static expression stored that will allow getting your "net" out, and let the getter of the "net" property run this expression against this.

And how to inject an expression in a regular linq query? I've written a blog post about it. Basically, I create an expression extender that will update the L2S expression tree with the custom expression :) Extending LINQ selectors with custom expressions

Artiom Chilaru