How to get property Name using Expression Tree

recently during some dynamic work in ado.net Entity framework i came across a problem…

suppose here is our class

public class User
{
    #region View Properties
    public long Id { get; set; }
    public String Email { get; set; }
    #endregion
}

 

now an instance of our class is always persisted in a Store… and at some point say when system updates the value of User we need to run some custom validation rules and if a property doesn’t comply we need to revert its value to older one….

public static class Store
{
    public static string GetPreviousValue(this class classobject,propertyname)
    {
        //Do something
    }
}

 

but you want to specify something like (don’t confuse i am using here)

userinstance.Email = this.GetPreviousValue(userinstance.Email);
Since Email is a property name it will return value of Email field but we want the property name not the value how this will be done…..
we don’t want to hard code the property names.. so what next…. ummm Reflection?? again a NO because through reflection we will be able to only iterate properties with there names but we don’t know which property is our required one……
 
public static string GetPropertyName()
{
PropertyInfo[] properties = this.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);
 for (int i = 0; i < properties.Length; i++)
    {
        object propValue = properties[i].GetValue(this, null);
        if (object.ReferenceEquals(propValue,value))     
           {
            return properties[i].Name;
            }
    }
return null;
}
one thing its not a good approach 2ndly it will fail in case if a class has more than one same value…. so this is so dead….
what next well after going through a lot i found some thing very interesting using (as it came up in 3.5)
public class TypeOf<T>
    {
        public static string Property<TProp>(Expression<Func<T, TProp>> expression)
        {
            var body = expression.Body as MemberExpression;
            if (body == null) throw new ArgumentException("'expression' should be a member expression");
            return body.Member.Name;
        }
    }

 

and with this it works like a charm…

var propName = Nameof<SampleClass>.Property(e => e.Email);
userinstance.Email= propName;

Shout it kick it on DotNetKicks.com

Advertisements
  1. Get property name and type by pass it directly | PHP Developer Resource

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: