I'm a AutoMapper newb. My mappings are not working as expected and I'm sure I'm doing somthing wrong but can't figure it out. Sorry if this question is confusing, but i'll do my best to be clear. Lets say we have three classes:
public class Person
{
public ContactInfo1 Contact { get; set; }
}
public class ContactInfo1
{
public string Name { get; set; }
}
public class ContactInfo2
{
public string AnotherName { get; set; }
}
Now, I want to setup my mappings so that ContactInfo1 can map to and from ContactInfo2. And then I want to be able to map Person1 -> ContactInfo2 (which might look stange, but I need to do it anyway). I have tried the following mapping config:
var autoMapperConfig = new AutoMapper.MapperConfiguration(cfg =>
{
cfg.CreateMap<ContactInfo1, ContactInfo2>()
.ForMember(dest => dest.AnotherName, opt => opt.MapFrom(src => src.Name)).ReverseMap();
cfg.CreateMap<ContactInfo2, Person>()
.ForMember(dest => dest.Contact, opt => opt.MapFrom(src => src)).ReverseMap();
});
var mapper = autoMapperConfig.CreateMapper();
For the test data:
var testPerson = new Person();
testPerson.Contact = new ContactInfo1() { Name = "Person1" };
I do the following:
var contactInfo2Test = mapper.Map<Person, ContactInfo2>(testPerson);
This does NOT give me any errors, but contactInfo2Test.AnotherName is empty. Please advise! Thanks.
Please note that I realize I could go:
cfg.CreateMap<Person, ContactInfo2>() .ForMember(dest => dest.AnotherName, opt => opt.MapFrom(src => src.Contact.Name));
Bu then I would have mapped Contact1->Contact2 all over again, and in a more complex scenario I really want to avoid that.
Here's one way of doing it:
var autoMapperConfig = new AutoMapper.MapperConfiguration(cfg =>
{
cfg.CreateMap<ContactInfo1, ContactInfo2>()
.ForMember(dest => dest.AnotherName, opt => opt.MapFrom(src => src.Name))
.ReverseMap();
cfg.CreateMap<Person, ContactInfo2>()
.ConstructUsing((p, ctx) => ctx.Mapper.Map<ContactInfo2>(p.Contact));
});