为什么没有.ForMember的automapper无法处理嵌套对象?

时间:2018-08-21 10:03:46

标签: c# asp.net asp.net-core .net-core automapper

Person类包含许多嵌套对象。当我尝试使用自动映射器将此“ Person”类映射到PersonDTO时,如果我不这样指定每个属性,它将不会映射嵌套对象的值:

CreateMap<Person, PersonDto>()
 .ForMember(dest => dest.Mobilenumber, opt => opt.MapFrom(src => src.ContactInfo.Mobilenumber))
        .ForMember(dest => dest.Companyname, opt => opt.MapFrom(src => src.Company.Companyname)).ReverseMap();

Automapper是否应该仅从如下所示的映射并展平对象中就不能感觉到这一点?

CreateMap<ContactInfo, ContactInfoDto>().ReverseMap();

public class Person : EntityBase
{
    public Person()
    {
        this.CreationTimeUTC  = DateTime.UtcNow;
        this.UpdateTimeUTC = DateTime.UtcNow;
    }
    public int PersonId {get; private set;}
    public string Firstname { get; set; }
    public string Lastname { get; set; }
    public string Email {get; set;}
    public DateTime CreationTimeUTC { get; private set; }
    public DateTime UpdateTimeUTC { get; set; }

    //ContactGroup many-many
    public ICollection<ContactGroup> ContactGroups { get; } = new List<ContactGroup>();

    //Contact-FK
    public ContactInfo ContactInfo {get; set;}

    //Company-FK
    public int CompanyId {get; set;}
    public Company Company {get; set;}


    public override string ToString()
    {
        return Firstname + " " + Lastname;
    }
 }

public class ContactInfo : EntityBase
{
    public ContactInfo()
    {
        this.CreationTimeUTC  = DateTime.UtcNow;
        this.UpdateTimeUTC = DateTime.UtcNow;
    }
    public int ContactInfoId {get; private set;}
    public DateTime CreationTimeUTC { get; private set; }

    public DateTime UpdateTimeUTC { get; set; }
    public string Mobilenumber { get; set; }

    //Person-FK
    public int PersonId {get; set;}
    public Person Person {get; set;}


    public override string ToString()
    {
        return Mobilenumber;
    }
}

1 个答案:

答案 0 :(得分:0)

AutoMapper确实支持自动投影,但是您实际上必须遵循约定才能使用自动投影。具体来说,它要求目标属性名称必须在源中适当属性的路径之后命名。换句话说,要自动映射ContactInfo.MobileNumber,您需要在目的地上命名为ContactInfoMobileNumber的属性。由于您只有MobileNumber,因此AutoMapper没有足够的信息来确定是否应从ContactInfo那里投影值。