If i have a product.
var p = new Product { Price = 30 };
and i have the following linq query.
var q = repo.Products().Where(x=>x.Price == p.Price).ToList()
In an IQueryable provider, I get a MemberExpression back for the p.Price which contains a Constant Expression, however I can't seem to get the value "30" back from it.
Update I have tried this but it doesn't seem to work.
var memberExpression = (MemberExpression)GetRootConstantExpression(m);
var fi = (PropertyInfo)memberExpression.Member;
var val = fi.GetValue(((ConstantExpression)memberExpression.Expression).Value, null);
Cheers.
And what exactly are you trying to accomplish?
Because to access the value of
Price
, you'd have to do something like:The constant expression is going to point to a capture-class generated by the compiler. I've not included the decision points etc, but here's how to get 30 from that:
price
is now30
. Note that I'm assuming thatPrice
is a property, but in reality you would write aGetValue
method that handles property / field.If you had a class:
and an instance of the object:
You can get the value of Id using an Expression using the following code:
value will contain "7"
q
is of typeList<Product>
. The List doesn't have a Price property - only the individual Products.The first or last Product will have a price.
If you know there's only one in the collection you can also flatten it using Single
Can you use the following:
You can compile and invoke a lambda expression whose body is the member access:
Local evaluation is a common technique when parsing expression trees. LINQ to SQL does this exact thing in quite a few places.