Skip to content

Instantly share code, notes, and snippets.

@kamranayub
Created April 21, 2011 21:00
Show Gist options
  • Save kamranayub/935461 to your computer and use it in GitHub Desktop.
Save kamranayub/935461 to your computer and use it in GitHub Desktop.
This ProxyConverter can be used with AutoMapper to help when converting Entity Framework proxied objects (i.e. DynamicProxy_xxxxxxx). Room for improvement. See: http://stackoverflow.com/questions/3441916/automapper-mapping-issue-with-inheritance-and-abstr
// See: http://stackoverflow.com/questions/3441916/automapper-mapping-issue-with-inheritance-and-abstract-base-class-on-collection/5749579#5749579
//
// For use with AutoMapper
public class ProxyConverter<TSource, TDestination> : ITypeConverter<TSource, TDestination>
where TSource : class
where TDestination : class
{
public TDestination Convert(ResolutionContext context)
{
// Get dynamic proxy base type
var baseType = context.SourceValue.GetType().BaseType;
// Return regular map if base type == Abstract base type
if (baseType == typeof(TSource))
baseType = context.SourceValue.GetType();
// Look up map for base type
var destType = (from maps in Mapper.GetAllTypeMaps()
where maps.SourceType == baseType
select maps).FirstOrDefault().DestinationType;
return Mapper.DynamicMap(context.SourceValue, baseType, destType) as TDestination;
}
}
// Usage (AutoMapper configuration)
Mapper.CreateMap<AbstractClass, AbstractViewModel>()
.ConvertUsing(new ProxyConverter<AbstractClass, AbstractViewModel>());
// Add derived maps here (note: do not use .Include<> syntax)
Mapper.CreateMap<DerivedClassA, DerivedClassAViewModel>();
// Usage (when mapping)
return Mapper.Map<IEnumerable<AbstractClass>, IEnumerable<AbstractClassViewModel>>(listOfDerivedClasses);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment