Using AutoMapper to unflatten a DTO

前端 未结 7 937
执念已碎
执念已碎 2020-11-28 07:52

I\'ve been trying to use AutoMapper to save some time going from my DTOs to my domain objects, but I\'m having trouble configuring the map so that it works, and I\'m beginni

7条回答
  •  北海茫月
    2020-11-28 08:27

    In addition to sydneyos answer and according to Trevor de Koekkoek comment, two way mapping is possible this way

    public class Person
    {
        public string Name { get; set; }
        public Address Address { get; set; }
    }
    
    public class Address
    {
        public string Street { get; set; }
        public string City { get; set; }
        public string State { get; set; }
    }
    
    public class PersonViewModel
    {
        public string Name { get; set; }
        public string AddressStreet { get; set; }
        public string AddressCity { get; set; }
        public string AddressState { get; set; }
    }
    

    Automapper mappings

    Mapper.Initialize(cfg => cfg.RecognizePrefixes("Address"));
    Mapper.CreateMap();
    Mapper.CreateMap();
    Mapper.CreateMap()
        .ForMember(dest => dest.Address, opt => opt.MapFrom( src => src )));
    

    If you implement NameOf class, you can get rid of prefix magic string

    Mapper.Initialize(cfg => cfg.RecognizePrefixes(Nameof.Property(x => x.Address)));
    

    EDIT: In C# 6

    Mapper.Initialize(cfg => cfg.RecognizePrefixes(nameof(Person.Address)));
    

提交回复
热议问题