AutoMapper and inheritance - How to Map?

前端 未结 5 762
北荒
北荒 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:47

    You will need to create DTO classes that match your domain classes like this:

    public class DTO
    {
        public string Name;
    }
    
    public class DTO_A : DTO
    {
        public int Number { get; set; }
    }
    
    public class DTO_B : DTO
    {
        public string Description { get; set; }
    }
    

    You then need to change your mappings to this:

            Mapper.CreateMap()
                .Include()
                .Include();
    
            Mapper.CreateMap();
    
            Mapper.CreateMap();
    
            Mapper.AssertConfigurationIsValid();
    

    Once this is done, then the following will work:

            var baseList = new List
            {
                new Base {Name = "Base"},
                new ClassA {Name = "ClassA", Number = 1},
                new ClassB {Name = "ClassB", Description = "Desc"},
            };
    
            var test = Mapper.Map,IList>(baseList);
            Console.WriteLine(test[0].Name);
            Console.WriteLine(test[1].Name);
            Console.WriteLine(((DTO_A)test[1]).Number);
            Console.WriteLine(test[2].Name);
            Console.WriteLine(((DTO_B)test[2]).Description);
            Console.ReadLine();
    

    Unfortunately this does mean that you have an unwanted cast, but I don't think there's much that you can do about that.

提交回复
热议问题