【问题标题】:Can AutoMapper map to a different destination property when one matches source?当一个匹配源时,AutoMapper 可以映射到不同的目标属性吗?
【发布时间】:2016-01-26 19:06:25
【问题描述】:

例如,假设我有以下...

public class TheSource
{
    public string WrittenDate { get; set; }
}

public class TheDestination
{
    public string CreateDate { get; set; }
    public DateTime WrittenDate { get; set;}
}

我有这样的映射......

Mapper.CreateMap<TheSource, TheDestination>()
    .ForMember(dest => dest.CreateDate, opt => opt.MapFrom(src => src.WrittenDate));

问题:Automapper 是否尝试将TheSource.WrittenDate 映射到TheDestination.WrittenDate 而不是我在.ForMember 中指定的TheDestination.CreateDate

-- 我问这个是因为我从上面的 CreateMap 行中得到了一个 AutoMapper DateTime 异常。

【问题讨论】:

    标签: c# automapper


    【解决方案1】:

    Automapper 是否尝试将 TheSource.WrittenDate 映射到 TheDestination.WrittenDate 而不是我在 .ForMember 中指定的 TheDestination.CreateDate?

    不是代替TheDestination.CreateDate

    • Automapper 会将 src.WrittenDate 映射到 dest.CreateDate,因为您已明确指定。

    • 它会将src.WrittenDate 映射到dest.WrittenDate,因为按照惯例,如果您不另外指定,则在创建映射时,具有相同名称的属性将相互映射。

    要覆盖此行为,您可以明确告诉 Automapper 忽略 dest.WrittenDate,如下所示:

    Mapper.CreateMap<TheSource, TheDestination>()
        .ForMember(dest => dest.CreateDate, opt => opt.MapFrom(src => src.WrittenDate))
        .ForMember(dest => dest.WrittenDate, opt => opt.Ignore());
    

    【讨论】:

    • 效果很好。谢谢你。我现在知道了。虽然我指定 src.WrittenDate 转到 dest.CreateDate,但 AutoMapper 还想将 src.WrittenDate 映射到 dest.WrittenDate。有道理。
    猜你喜欢
    • 2013-06-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-01-11
    • 1970-01-01
    • 2020-05-04
    相关资源
    最近更新 更多