Skip to content

Naked Objects for .NET
Syndicate content
(If you wish to comment on any post please use the forum: http://forum.nakedobjects.net)
Updated: 1 day 2 hours ago

Creating Expressions dynamically to overcome compiler restrictions

Fri, 04/15/2011 - 10:33

Using lamdas to identify a property in a type safe manner has become a popular idiom in the latest microsoft APIs. So for example in EF 4.1 to ignore a property you can enter

public class Address {
   public Person Property {  protected get; set; }     
}
...
modelBuilder.ComplexType<Address>().Ignore(a => a.Property);

However the compiler will only allow you to do this for properties with
an accessible getter. So if a property is protected this would be illegal.
Assuming that there is no alternative API and the method will accept a
protected property a workaround is to dynamically create the expression. 

For example 

var prop = (typeof(Address)).GetProperty("Property");
ParameterExpression p = Expression.Parameter((typeof(Address)), "p");
MemberExpression body = Expression.Property(p, prop);
LambdaExpression expr = Expression.Lambda(body, p);

modelBuilder.ComplexType<Address>().
                   Ignore((Expression<Func<Address, Person>>)expr);
Categories: Companies