目前,我需要映射以下对象
目标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 (列表)
发布于 2017-03-23 09:43:32
为了将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); https://stackoverflow.com/questions/42933975
复制相似问题