gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 21:52:10 26 4
gpt4 key购买 nike

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

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?

-- 我问这个是因为我从上面的 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 因为按照惯例,如果您不另外指定,则具有相同名称的属性将创建 map 时相互映射。

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

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

关于c# - 当匹配源时,AutoMapper 可以映射到不同的目标属性吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35021812/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com