2

我有一些具有大量属性的对象。当我开始使用 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));
4

1 回答 1

2

圣钼。几乎所有这些映射都是不必要的。MapFrom 仅适用于名称匹配时,而不适用于匹配时。即使它们不匹配,我也需要一个非常好的理由不使用“BodyPlain”,它会在没有配置的情况下映射,而不是“PlainBody”,它与“Body.Plain”不匹配。

于 2013-10-16T13:13:09.450 回答