[英]how to map only if destination object doesn't have a value in Automapper
I have a mapper in place and I need to perform a conditional mapping, Condition is, map the value from source to destination only if the destination property value is null. How would I do that?我有一个映射器,我需要执行条件映射,条件是,map 仅当目标属性值为 null 时,才从源到目标的值。我该怎么做?
.ForMember(o => o.EmployeeId, opt => opt.MapFrom(u => u.EmployeeId))
I want to assign value to EmployeeId only if it does't have a value already.仅当 EmployeeId 还没有值时,我才想为它赋值。
The method of IMemberConfigurationExpression
.MapFrom()
has the overload that takes an IDestination void MapFrom<TResult>(Func<TSource, TDestination, TResult> mappingFunction);
IMemberConfigurationExpression
.MapFrom()
具有重载,该重载采用 IDestination void MapFrom<TResult>(Func<TSource, TDestination, TResult> mappingFunction);
In your mapping function you can check the destination object.在您的映射函数中,您可以检查目标对象。
Example:例子:
.ForMember(dest => dest.EmployeeId, opt => opt.MapFrom((src, dest) => dest.EmployeeId ?? src.EmployeeId))
It's should be help you.应该能帮到你
CreateMap<YOURMODEL,YOURMODEL2>()
.ForMember(dest => dest.EmployeeId, opt => {
opt.PreCondition(src => src.EmployeeId != null);
opt.MapFrom(src => src.EmployeeId);
Other way另一种方式
CreateMap<SourceClass, TargetClass>()
.ForMember(d => d.EmployeeId, o => o.MapFrom(s => s.EmployeeId))
.ForAllMembers(o => o.Condition((src, dest, value) => value != null));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.