Skip to content

Instantly share code, notes, and snippets.

@schotime
Created January 11, 2011 22:04
Show Gist options
  • Save schotime/775251 to your computer and use it in GitHub Desktop.
Save schotime/775251 to your computer and use it in GitHub Desktop.
public class AutoMapperProfile : Profile
{
protected override void Configure()
{
CreateMap<DateTime, FormattedDateTime>().ConvertUsing<FormattedDateConverter>();
CreateMap<string, bool>().ConvertUsing(x => x == "Y" || x.ToLowerInvariant() == "on" || x == "1");
DictionaryToClassConverter.ConvertFromDictionary(this, GetType().Assembly, x => x.ToLowerInvariant());
}
}
public static class DictionaryToClassConverter
{
public static void ConvertFromDictionary(Profile p, Assembly assembly, Func<string, string> propertyNameMapper)
{
var types = assembly
.GetTypes()
.Where(x => x.GetInterfaces().Where(y => y == typeof(IFlatSql)).Any())
.ToList();
var createMap = typeof(Profile).GetMethods(BindingFlags.Instance | BindingFlags.Public).Where(x => x.Name == "CreateMap" && x.IsGenericMethod).Single(); ;
var mapDictionary = typeof(DictionaryToClassConverter).GetMethods(BindingFlags.Static | BindingFlags.NonPublic).Where(x => x.Name == "MapDictionary").Single();
foreach (var type in types)
{
MethodInfo createMapGeneric = createMap.MakeGenericMethod(new[] { typeof(IDictionary), type });
var map = createMapGeneric.Invoke(p, new object[] {});
MethodInfo mapDictionaryGeneric = mapDictionary.MakeGenericMethod(new[] { type });
mapDictionaryGeneric.Invoke(null, new object[]{ map, propertyNameMapper });
}
}
private static void MapDictionary<T>(this IMappingExpression<IDictionary, T> exp, Func<string, string> propertyNameMapper)
{
foreach (PropertyInfo pi in typeof(T).GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic))
{
if (!pi.CanWrite)
continue;
var propertyName = propertyNameMapper(pi.Name);
exp.ForMember(pi.Name, cfg =>
{
cfg.Condition(r => r.Contains(propertyName));
cfg.MapFrom(r => r[propertyName]);
});
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment