简体   繁体   中英

Name convention in Automapper

I know that Automapper can automatically map from:

class SomeClassA 
{
    public int Id { get; set; }
    public B Member { get; set; }
}
class SomeClassB 
{
    public int Id { get; set; }
    public string Name { get; set; }
}

to:

class SomeClassADto 
{
    public int Id { get; set; }
    public int Member_Id { get; set; }
    public string Member_Name { get; set; }
} 

But how can I make Automapper map from my SomeClassADto to SomeClassA automatically?

No the prettiest thing in the world, but it does work. Downside is maintenance is a pain as you add properties to the DTO and class you need to update the mapping.

var config = new MapperConfiguration(x =>
{
    x.CreateMap<SomeClassADto, SomeClassB>()
        .ForMember(i => i.Id, i => i.MapFrom(src => src.Member_Id))
        .ForMember(i => i.Name, i => i.MapFrom(src => src.Member_Name));
    x.CreateMap<SomeClassADto, SomeClassA>()
        .AfterMap((s, d, r) => d.Member = r.Mapper.Map<SomeClassB>(s));
});
IMapper mapper = config.CreateMapper();

var foo = mapper.Map<SomeClassA>(new SomeClassADto() { Id = 1, Member_Id = 2, Member_Name = "Name" });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM