如何解决仅在目标值为null时映射
我是automapper的新手,仅当目标值为null时,我才尝试映射。我检查了文档,但它仅显示源值的条件。我可以知道如何在条件下检查目标值吗?
this.CreateMap<DtoObject,MyObject>()
.EqualityComparison((dto,o) =>
dto.id== o.id)
.ForMember(s => s.MyField,opt =>
{
//I want to Map only MyField of destination object is null,otherwise I don't want to map. But How can I get destination's MyField value?
});
解决方法
有两种方法可以达到这种效果。
首选方法是使用Automapper conditional Mapping:
CreateMap<DtoObject,MyObject>()
.ForMember(dest => dest.MyField,opt =>
{
opt.PreCondition((source,dest,ctx) => dest.MyField == null);
opt.MapFrom(src => src.MyField);
});
另一种方法是在映射过程中结合使用AfterMap
方法和Ignore
,就像这样。
CreateMap<DtoObject,MyObject>()
.ForMember(d => d.MyField,a => a.Ignore())
.AfterMap((source,destination) =>
{
if (destination.MyField == null)
{
destination.Name = source.MyField;
}
});
这将告诉AutoMapper在映射过程中忽略该属性,并在后续映射期间执行一些自定义逻辑。
,看看AutoMapper Conditional mapping。
使用PreCondition
可以访问source
和destination
并设置应映射属性的条件:
this.CreateMap<DtoObject,MyObject>()
.EqualityComparison((dto,o) =>
dto.id== o.id)
.ForMember(s => s.MyField,opt =>
{
opt.PreCondition((dest,src) => dest.SomeDestinationProperty == null);
opt.MapFrom(src => src.SomeSourceProperty);
});
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。