首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >消除联接表的AutoMap

消除联接表的AutoMap
EN

Stack Overflow用户
提问于 2017-03-21 17:15:08
回答 1查看 493关注 0票数 0

目前,我需要映射以下对象

目标1

代码语言:javascript
复制
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

代码语言:javascript
复制
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 (列表)

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2017-03-23 09:43:32

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

代码语言:javascript
复制
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,则可以使用以下映射:

代码语言:javascript
复制
    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>();

下面是一个使用测试示例:

代码语言:javascript
复制
    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); 
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42933975

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档