AutoMap 消除连接 Table

AutoMap To Eliminate Join Table

目前我有以下需要映射的对象

对象 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; }
}

我正在尝试将其映射到以下对象

对象 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; }
}

基本上我想在映射时消除 PhoneToCustomer 对象。我需要 ContactInfoModel.Phones 映射到 ContactInfo.PhoneToCustomer.Phone(列出)

为了将 ContactInfo 映射到 ContactInfoModel,您需要添加以下映射:

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

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

如果您想将 ContactInfoModel 反之映射到 ContactInfo,您可以使用以下映射:

    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>();

这是一个使用测试示例:

    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);