AutoMapper and inheritance - How to Map?

前端 未结 5 771
北荒
北荒 2020-12-12 22:24

Have this scenario:

public class Base {  public string Name; }

public Class ClassA :Base {  public int32 Number;  }

public Class ClassB :Base { public st         


        
5条回答
  •  没有蜡笔的小新
    2020-12-12 22:57

    For your scenario you have to use IMappingExpression.ConvertUsing method. By using it you can provide appropriate type for newly created object. Please, look at my example (pretty well fit your scenario):

    using System;
    using System.Linq;
    using AutoMapper;
    
    namespace ConsoleApplication19
    {
        internal class Program
        {
            private static void Main(string[] args)
            {
                //mapping
                Mapper.Initialize(expression =>
                {
                    expression.CreateMap()
                        .ForMember(@class => @class.IdOnlyInDestination,
                            configurationExpression => configurationExpression.MapFrom(dto => dto.Id))
                        .ConvertUsing(dto =>//here is the function that creates appropriate object
                        {
                            if (dto.Id%2 == 0) return Mapper.Map(dto);
                            return Mapper.Map(dto);
                        });
    
                    expression.CreateMap()
                        .IncludeBase();
    
                    expression.CreateMap()
                        .IncludeBase();
                });
    
                //initial data
                var arrayDto = Enumerable.Range(0, 10).Select(i => new DTO {Id = i}).ToArray();
    
                //converting
                var arrayResult = Mapper.Map(arrayDto);
    
                //output
                foreach (var resultElement in arrayResult)
                {
                    Console.WriteLine($"{resultElement.IdOnlyInDestination} - {resultElement.GetType().Name}");
                }
    
                Console.ReadLine();
            }
        }
    
        public class DTO
        {
            public int Id { get; set; }
    
            public int EvenFactor => Id%2;
        }
    
        public abstract class NumberBase
        {
            public int Id { get; set; }
            public int IdOnlyInDestination { get; set; }
        }
    
        public class OddNumber : NumberBase
        {
            public int EvenFactor { get; set; }
        }
    
        public class EvenNumber : NumberBase
        {
            public string EventFactor { get; set; }
        }
    }
    

提交回复
热议问题