0

Currently I have the following Objects that I need to map

OBJECT 1

public class ContactInfo 
{
    public int ContactInfoId { get; set; }
    public ICollection<PhoneToCustomer> Phones { get; set; }
}

public class PhoneToCustomer
{
    public int ContactInformationId { get; set; }
    public Phone Phone { get; set; }
    public int PhoneId { get; set; }
}

public class Phone
{
    public int PhoneId { get; set; }
    public long Number { get; set; }
    public PhoneType Type { get; set; }
    public string Extension { get; set; }
    public string CountryCode { get; set; }
    public PhoneRestrictions Restrictions { get; set; }
    public bool Primary { get; set; }
}

I am trying to map it to the following object

OBJECT 2

public class ContactInfoModel
{
    public int ContactInfoId { get; set; }
    public ICollection<PhoneModel> Phones { get; set; }
}

public class PhoneModel
{
    public int PhoneId { get; set; }
    public long Number { get; set; }
    public PhoneType Type { get; set; }
    public string Extension { get; set; }
    public string CountryCode { get; set; }
    public PhoneRestrictions Restrictions { get; set; }
    public bool Primary { get; set; }
}

Essentially I am wanting to eliminate the PhoneToCustomer object when mapping it. I need the ContactInfoModel.Phones to map to ContactInfo.PhoneToCustomer.Phone (to list)

Brandon Turpy
  • 883
  • 1
  • 10
  • 32

1 Answers1

1

In order to map ContactInfo to ContactInfoModel you need to add the following mappings:

AutoMapper.Mapper.CreateMap<Phone, PhoneModel>();

AutoMapper.Mapper.CreateMap<ContactInfo, ContactInfoModel>()
                .ForMember(x => x.Phones, y => y.MapFrom(z => z.Phones.Select(q => q.Phone)));

If you want to map vice versa from ContactInfoModel to ContactInfo you can use the following mappings:

    AutoMapper.Mapper.CreateMap<PhoneModel, Phone>();

    AutoMapper.Mapper.CreateMap<PhoneModel, PhoneToCustomer>()
        .ForMember(x => x.Phone, y => y.MapFrom(z => z))
        .ForMember(x => x.ContactInformationId, y => y.Ignore())
        .ForMember(x => x.PhoneId, y => y.Ignore());

    AutoMapper.Mapper.CreateMap<ContactInfoModel, ContactInfo>();

Here is a test example of usage:

    var contactInfo = new ContactInfo()
    {
        ContactInfoId = 1, 
        Phones = new List<PhoneToCustomer>()
        {
            new PhoneToCustomer()
            {
                 Phone = new Phone(){CountryCode = "Code1", Extension = "Extension1"},
            },
            new PhoneToCustomer()
            {
                 Phone = new Phone(){CountryCode = "Code2", Extension = "Extension2"}
            }
        }
    };

var contactInfoModel = AutoMapper.Mapper.Map<ContactInfoModel>(contactInfo);

var contactInfoBack = AutoMapper.Mapper.Map<ContactInfo>(contactInfoModel); 
Oleg Lukash
  • 291
  • 2
  • 7