是否可以使用AutoMapper自动映射除少数复杂属性之外的所有属性?

时间:2013-10-16 03:35:45

标签: c# mapping automapper automapper-3

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

1 个答案:

答案 0 :(得分:1)

圣洁的莫莉。几乎所有这些映射都是不必要的。 MapFrom仅适用于名称​​不匹配的情况,而不适用于名称​​不的情况。即使他们不匹配,我也需要一个非常好的理由不让#34; BodyPlain&#34;,这将在没有配置的情况下进行映射,而不是&#34; PlainBody&#34;,没有匹配&#34; Body.Plain&#34;。