views:

41

answers:

2

I am using AutoMapper where it has:

.ForMember( dest => dest.id, opt => opt.MapFrom(src => src.id))

Using the far right expression src => src.id, if I have a string variable with the property's name, how would I choose the property by it?

I tried this:

src => propertyName

Then had to laugh when the value was "id".

+1  A: 

If you have the name of the property you wish to access, you would use reflection to get MemberInfo and then invoke the property from the MemberInfo.

src => src.GetType().GetProperty(propertyName).GetGetMethod().Invoke(src, new object[] {})

Of course, this tidbit assumes src has properties and that propertyName identifies a property on the object.

Les
Sweet, looking forward to the answer.
Dr. Zim
+3  A: 

You can use reflection to get a property by name:

private R GetProperty<T, R>(T obj, string propertyName)
{
    PropertyInfo pi = obj.GetType().GetProperty(propertyName);
    return (R)pi.GetValue(obj, null);
}

Which you would use in AutoMapper like this:

.ForMember( dest => dest.id, opt => opt.MapFrom(src => GetProperty(src, propertyName)))
dahlbyk
+1 But this code can be improved because currently it's not working for static properties/fields.
Danny Chen
I interpret the AutoMapper use case as suggesting it only needs to get instance members from src, but you're certainly right that the same technique would work for static members.
dahlbyk
Everything worked, with the exception of having the source be a "var" .Select() projection, which has a type of "object", and AutoMapper didn't find any fields to map. LOL.
Dr. Zim
Updated with a generic parameter, though GetType() should return the most specific type. Unless I'm misunderstanding you?
dahlbyk
Your part worked fine. Way back to how I am using your code, I am trying to Automap between a POCO and a set of arbitrary properties selected by .Select( p => new {p.custid, p.custname}) (for example). AutoMapper doesn't find any properties that are the same names, even though they exist.
Dr. Zim
For example, I have a Customer POCO where I try to map between a var a = Customer.Select( p => new {p.ID, p.name, p.phone}); and a var b = new Customer();
Dr. Zim
Glad to help. You'll probably want to create a new question (or update an existing one) to discuss your other issue.
dahlbyk