Automapper : mapping issue with inheritance and abstract base class on collections with Entity Framework 4 Proxy Pocos

后端 未结 5 842
轻奢々
轻奢々 2020-12-07 20:23

I am having an issue using AutoMapper (which is an excellent technology) to map a business object to a DTO where I have inheritance off of an abstract base class within a co

5条回答
  •  情话喂你
    2020-12-07 21:27

    Building on Olivier's response, I could not get his to work in my context... it kept going in an infinite loop and threw a StackOverflowException.

    In this example, AbstractClass is my base class and AbstractViewModel is my base view model (not marked as abstract mind you).

    However, I did get it to work using this hackish looking converter:

        public class ProxyConverter : ITypeConverter
            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
    
        Mapper.CreateMap()
            .ConvertUsing(new ProxyConverter());
    

    So, a DerivedClassA will map normally, but a DynamicProxy_xxx will also map properly as this code inspects its base type (DerivedClassA).

    Please, please, please show me that I don't have to do this crazy lookup crap. I don't know enough AutoMapper to fix Olivier's answer properly.

提交回复
热议问题