【问题标题】:Why does automapper not handle nested objects without .ForMember?为什么 automapper 不处理没有 .ForMember 的嵌套对象?
【发布时间】:2018-08-21 10:03:46
【问题描述】:

Person 类包含许多嵌套对象。当我尝试使用 automapper 将此“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;
    }
}

【问题讨论】:

  • 为什么要这样?你当然可以实现它,但是你必须考虑要深入多少层,如果找到多个选项该怎么办,如果你不想从子对象映射怎么办,等等。你'正在做许多人所做的事情,并假设应该发生某些事情,因为它在一种特定情况下很方便。它并不像您想象的那么方便。
  • built-in 是什么,possible 是什么。

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


【解决方案1】:

AutoMapper 确实支持自动投影,但您必须真正遵循约定才能使用它。具体来说,它要求目标属性名称必须以源中相应属性的路径命名。换句话说,要自动映射ContactInfo.MobileNumber,您需要在目的地上拥有一个名为ContactInfoMobileNumber 的属性。由于您只有MobileNumber,因此AutoMapper 没有足够的信息来确定它应该将ContactInfo 的值投影到那里。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-20
    • 1970-01-01
    • 1970-01-01
    • 2016-03-30
    • 2021-10-01
    相关资源
    最近更新 更多