当匹配源时,AutoMapper 可以映射到不同的目的地 属性 吗?
Can AutoMapper map to a different destination property when one matches source?
例如,假设我有以下...
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 异常。
Is the Automapper trying to map the TheSource.WrittenDate to TheDestination.WrittenDate instead of TheDestination.CreateDate as I specified in the .ForMember?
不是 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());
例如,假设我有以下...
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 异常。
Is the Automapper trying to map the TheSource.WrittenDate to TheDestination.WrittenDate instead of TheDestination.CreateDate as I specified in the .ForMember?
不是 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());