I'm trying to convert my AutoMapper code to be more fluent-api like, e.g. existing code:
Model.Foo target = Mapper.Map<Contract.Foo, Model.Foo>(source);
What I'd like the code to look like is this
Model.Foo target = source.ConvertTo<Model.Foo>();
I started writing my extension method, but I can't seem to get this to work.
public static class AutoMapperConverterExtension
{
public static T ConvertTo<T>(this string source) where T : new()
{
Type sourceType = Type.GetType(source);
if (IsMapExists<sourceType, T>()) // complains here! cannot resolve 'sourceType'. If I use inline, won't compile.
{
return Mapper.Map<T>(source);
}
throw new NotImplementedException("type not supported for conversion");
}
public static bool IsMapExists<TSource, TDestination>()
{
return (AutoMapper.Mapper.FindTypeMapFor<TSource, TDestination>() != null);
}
}