是否可以使用自动映射器自动映射除一些复杂属性之外的所有属性

本文关键字:映射 属性 复杂 可以使 是否 | 更新日期: 2023-09-27 18:35:27

我有一些具有大量属性的对象。当我开始使用AutoMapper时,我试图只映射一些嵌套对象来了解它是如何工作的。我一直认为它会映射源和目标处具有相同名称的属性。但是,似乎一旦我有一些 ForMember() 规则,它只会映射我有规则的属性。

有没有办法只指定几个规则,其中源对象和目标对象不同?还是我必须明确并映射每个属性?

Mapper.CreateMap<MessageWireFormat, Message>()
    .ForMember(dest => dest.PlainBody, opt => opt.MapFrom(src => src.Body.Plain))
    .ForMember(dest => dest.ParsedBody, opt => opt.MapFrom(src => src.Body.Parsed))
    .ForMember(dest => dest.RichBody, opt => opt.MapFrom(src => src.Body.Rich))
    .ForMember(dest => dest.Excerpt, opt => opt.MapFrom(src => src.ContentExcerpt))
    .ForMember(dest => dest.AttachmentCount, opt => opt.MapFrom(src => src.Attachments.Length))
    .ForMember(dest => dest.Id, opt => opt.MapFrom(src => src.Id))
    .ForMember(dest => dest.Url, opt => opt.MapFrom(src => src.Url))
    .ForMember(dest => dest.WebUrl, opt => opt.MapFrom(src => src.WebUrl))
    .ForMember(dest => dest.NetworkId, opt => opt.MapFrom(src => src.NetworkId))
    .ForMember(dest => dest.GroupId, opt => opt.MapFrom(src => src.GroupId))
    .ForMember(dest => dest.SystemMessage, opt => opt.MapFrom(src => src.SystemMessage))
    .ForMember(dest => dest.Privacy, opt => opt.MapFrom(src => src.Privacy))
    .ForMember(dest => dest.DirectMessage, opt => opt.MapFrom(src => src.DirectMessage))
    .ForMember(dest => dest.SenderType, opt => opt.MapFrom(src => src.SenderType))
    .ForMember(dest => dest.SenderId, opt => opt.MapFrom(src => src.SenderId))
    .ForMember(dest => dest.CreatedAt, opt => opt.MapFrom(src => src.CreatedAt))
    .ForMember(dest => dest.ClientType, opt => opt.MapFrom(src => src.ClientType))
    .ForMember(dest => dest.ClientUrl, opt => opt.MapFrom(src => src.ClientUrl))
    .ForMember(dest => dest.RepliedToId, opt => opt.MapFrom(src => src.RepliedToId))
    .ForMember(dest => dest.Language, opt => opt.MapFrom(src => src.Language));

是否可以使用自动映射器自动映射除一些复杂属性之外的所有属性

神圣的莫利。几乎所有这些映射都是不必要的。MapFrom 仅在名称不匹配时才适用,而不是在名称不匹配时适用。即使它们不匹配,我也需要一个很好的理由来不使用"BodyPlain",它将在没有配置的情况下进行映射,而不是与"Body.Plain"不匹配的"PlainBody"。