views:

28

answers:

1

What would the C# code be to create a (service) method to return an object (ViewModel for DDL) using AutoMapper and provide the two field names as parameters?

DDL is for a Drop Down List:

public class DDLitems {
    public string text {get;set;}
    public string value {get;set}
}

My horrible pseudo C# code idea: (yea no idea how to do this yet):

public IList<DDLobject> AutoMapDDLvalue( IList<object> source,
                                         type objectClass.textFieldName,
                                         type objectClass.valueFieldName)
{
    var EntityRepository = new EntityRepository();
    Mapper.CreateMap<source.type, DDLobject>()
          .ForMember(dest => dest.text, 
                      opt => opt.MapFrom(src => src.objectClass.textFieldName))
          .ForMember(dest => dest.value, 
                      opt => opt.MapFrom(src => src.objectClass.valueFieldName));
    return Mapper.Map<IList<source>, IList<DDLobject>>(EntityRepository.Get());
 }

I just thought that the field types would need to be converted to string. I guess we could add a generic .ToString() to each.

+1  A: 

I have absolutely no experience with AutoMapper, but I guess the problem boils down to getting a property from an object, when you know the property name only at runtime.

If that is the question, that's what reflection is for :)

You can get a property out of an object using this:

public object GetProperty(object obj, string propertyName)
{
  PropertyInfo pi = obj.GetType().GetProperty(propertyName);
  object value = pi.GetValue(o, null);
  //or object value = pi.GetGetMethod().Invoke(obj, null)
  return value;
}
SWeko
Yep. This really has nothing to do with AutoMapper, other than to clarify the parameters needed. Nice code.
Dr. Zim