自动映射将相关源映射到一个目标并将其展平

时间:2018-08-27 04:02:04

标签: c# asp.net-mvc automapper

我有以下数据库对象:

public class LinkedContact
{
    public int LinkedContactID { get; set; }
    public Nullable<int> ContactID { get; set; }
    public Nullable<int> ContactTypeID { get; set; }
    public Nullable<bool> Deleted { get; set; }

    public virtual Contact Contact { get; set; }
    public virtual ContactType ContactType { get; set; }
}

public class Contact
{
    public Contact()
    {
        this.LinkedContact = new HashSet<LinkedContact>();
    }

    public int ContactID { get; set; }
    public string DisplayName { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public Nullable<bool> Deleted { get; set; }
    public virtual ICollection<LinkedContact> LinkedContact { get; set; }
}

public class ContactType
{
    public ContactType()
    {
        this.LinkedContact = new HashSet<LinkedContact>();
    }

    public int ContactTypeID { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
    public virtual ICollection<LinkedContact> LinkedContact { get; set; }
}

我想将其映射到以下DTO

public class ContactDTO
{
    public int ContactID { get; set; }
    public string DisplayName { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public ContactTypeDTO ContactType { get; set; }
}

public class ContactTypeDTO
{
    public int ContactTypeID { get; set; }
    public string Name { get; set; }
    public string Description { get; set; }
}

因此,基本上,Contact Type中的Linked Contact应该映射到Contact DTO。最终用户将仅看到联系人视图模型,并且不知道Linked Contact以及结构。谁能帮助我进行映射配置。我没有运气尝试过以下内容

CreateMap<Contact, ContactDTO>().ReverseMap();
CreateMap<LinkedContact, ContactDTO>()
CreateMap<ContactType, ContactTypeDTO>().ReverseMap();

2 个答案:

答案 0 :(得分:1)

通过此链接查看,sample很好

CreateMap<LinkedContact, ContactDTO>()
                .ForMember(dest => dest.DisplayName, opts => opts.MapFrom(src => src.Contact.DisplayName))
                .ForMember(dest => dest.FirstName, opts => opts.MapFrom(src => src.Contact.FirstName))
                .ForMember(dest => dest.LastName, opts => opts.MapFrom(src => src.Contact.LastName))

另一个选择:

Mapper.Initialize(cfg =>
            {
                cfg.CreateMap<Contact, ContactDTO>().ReverseMap();
                cfg.CreateMap<ContactType, ContactTypeDTO>().ReverseMap();
                cfg.CreateMap<LinkedContact, ContactDTO>().ConvertUsing(src =>
                {
                    var contact = Mapper.Map<Contact, ContactDTO>(src.Contact);
                    contact.ContactType = Mapper.Map<ContactType, ContactTypeDTO>(src.ContactType);
                    return contact;
                });
            });

答案 1 :(得分:1)

最后,我使用以下配置同时映射了 python helloworld.py Contact。将其留给希望为同一事物寻找答案的人:

Contact Type