Here is the example: Entities:
public class Contact
{
public int Id { get; set; }
......
public ICollection<ContactDetail> ContactDetails { get; set; }
}
public class ContactDetail
{
public Guid Id { get; set; }
public int ContactId { get; set; }
public ContactDetailTypes ContactDetailType { get; private set; }
public string Email { get; set; }
public string Address { get; set; }
public string Phone { get; set; }
......
}
public enum ContactDetailTypes : byte
{
Email = 1,
Phone = 2,
Address = 3,
......
}
ViewModels:
public class ContactViewModel
{
public int Id { get; set; }
......
public ICollection<ContactEmailViewModel> ContactEmails { get; set; }
public ICollection<ContactPhoneViewModel> ContactPhones { get; set; }
public ICollection<ContactAddressViewModel> ContactAddresses { get; set; }
}
public class ContactEmailViewModel
{
public Guid Id { get; set; }
public int ContactId { get; set; }
public string Email { get; set; }
}
public class ContactPhoneViewModel
{
public Guid Id { get; set; }
public int ContactId { get; set; }
public string Phone { get; set; }
}
public class ContactAddressViewModel
{
public Guid Id { get; set; }
public int ContactId { get; set; }
public string Address { get; set; }
}
I want to map ContactDetail to ContactEmailViewModel, ContactPhoneViewModel, ContactAddressViewModel:
CreateMap<ContactDetail, ContactEmailViewModel>()
.ForMember(dest => dest.Id, opts =>
{
opts.PreCondition(s => s.ContactDetailType == ContactDetailTypes.Email);
opts.MapFrom(src => src.Id);
})
.ForMember(dest => dest.ContactId, opts =>
{
opts.PreCondition(s => s.ContactDetailType == ContactDetailTypes.Email);
opts.MapFrom(src => src.ContactId);
})
.ForMember(dest => dest.Email, opts =>
{
opts.PreCondition(s => s.ContactDetailType == ContactDetailTypes.Email);
opts.MapFrom(src => src.Email);
});
(Phone, Address map are similar to above)
When I map Contact to ContactViewModel with the above profiles, the count of ContactEmails, ContactPhones, ContactAddresses are always 0. I thought automapper can check the detailType and map source to different destinations but failed.
If I create a ContactDetailViewModel with all the properties of those three view model, it is mapping all properties from ContactDetail to ContactDetailViewModel though.
How to achieve mapping one source to multiple destinations using Automapper in this example?
Update: I added a new map still no luck:
CreateMap<ICollection<ContactDetail>, ContactViewModel>()
.ForMember(dest => dest.ContactEmails, opts => opts.MapFrom(src => src.Where(s => s.ContactDetailType == ContactDetailTypes.Email)))
.ForMember(dest => dest.ContactPhones, opts => opts.MapFrom(src => src.Where(s => s.ContactDetailType == ContactDetailTypes.Phone)))
.ForMember(dest => dest.ContactAddresses, opts => opts.MapFrom(src => src.Where(s => s.ContactDetailType == ContactDetailTypes.Address)));
Just why did my post get devoted... I ask because I really couldn't find the answer after several attempts...