当一个匹配源时,AutoMapper可以映射到不同的目标属性吗?

时间:2016-01-26 19:06:26

标签: c# automapper

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

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,而不是TheDestination.CreateDate中我指定的.ForMember

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

1 个答案:

答案 0 :(得分:3)

  

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());
相关问题