[英]Custom mapping with Automapper where a field in destination is the concatenation of two fields in source
[英]Automapper 2 source fields mapped to 1 destination field
我有 2 个类要映射:class1 有字段 PaymentState 和 PaymentStateId
public int PaymentStateId { get; set; }
[ForeignKey(nameof(PaymentStateId))]
[InverseProperty(nameof(PaymentStateEntity.OrderEntities))]
public virtual PaymentStateEntity PaymentState { get; set; }
class2 具有同名 PaymentState 但枚举类型的字段
public PaymentState PaymentState { get; set; }
将 class1 映射到 class2 时出现无法映射字段 PaymentState 的错误:
Unable to create a map expression from
class1.PaymentState (Entities.PaymentStateEntity) to PaymentState.PaymentState (Enums.PaymentState)
Mapping types:
class1-> class2
Destination Member:
PaymentState
已经尝试过自定义映射字段,但我想现在有 2 个字段要映射到 1 个目的地字段这一事实造成了问题
CreateMap<class1, class2>()
.ForMember(dest => dest.PaymentState, opt => opt.MapFrom(src => src.PaymentStateId))
尽管让另一个源字段映射到目标字段,但忽略一个源字段的方法是什么?
我不认为错误原因是 2 个字段映射到 1 个目的地。 可能是因为目标和源之间的类型不同。 您应该检查日志错误是什么。 但你可以尝试使用
CreateMap<class1, class2>()
.ForMember(dest => dest.PaymentState, opt => opt.Ignore())
.ForMember(dest => dest.PaymentState, opt => opt.MapFrom(src => src.PaymentStateId))
此外,您可以通过将它们的项目设置为具有相同的值来转换 2 个枚举
.ForMember(dest => dest.PaymentState, opt => opt.MapFrom(src => (PaymentState)((int)src.PaymentState)))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.