如果并非所有源属性都匹配,则AutoMapper无法阻止空源值 [英] AutoMapper can't prevent null source values if not all source properties match

查看:132
本文介绍了如果并非所有源属性都匹配,则AutoMapper无法阻止空源值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

此处的目标是忽略空源值,而不要求源对象具有目标对象具有的所有字段.防止null似乎仅在对象之间的所有字段都匹配时才起作用.

The goal here is to ignore null source values, while not requiring the source object to have all the fields the destination object has. Preventing null seems to only work if ALL fields match between objects.

public class ApiStudent {
    public long Id { get; set; }   
    public string Name { get; set; }    
}

public class DomainStudent {
    public long Id { get; set; }
    public string Name { get; set; }
    public long SchoolId { get; set; }
}

当我运行以下映射时:

Mapper.CreateMap<ApiStudent, DomainStudent>()   
    .ForAllMembers(opt => opt.Condition(src => !src.IsSourceValueNull));

var api = new ApiStudent();
api.Id = 123;
api.Name = null;

var domain = new DomainStudent();
domain.Id = 123;
domain.Name = "Homer Simpson"; // goal is to prevent this from being written to null

domain = Mapper.Map(api, domain);
// I get an error here saying the SchoolId mapping is missing from ApiStudent

如果我从Mapping定义中删除了.ForAllMembers(opt => opt.Condition(src =>!src.IsSourceValueNull));" ,则不会得到该错误,但是那么.Name属性将被覆盖为null. 我在这里缺少什么使AutoMapper跳过目标对象而不是源对象上存在的属性?

If I remove the ".ForAllMembers(opt => opt.Condition(src => !src.IsSourceValueNull));" from the Mapping definition, I don't get the error, but then the .Name property will be overwritten to null. What am I missing here to get the AutoMapper to skip properties that exist on the destination object but not the source object?

推荐答案

此解决了!

https://github.com/AutoMapper/AutoMapper/issues/432

引用文章

我们刚刚从3.0.0升级到3.1.0,并开始遇到具有以下定义的映射问题:

We just upgraded from 3.0.0 to 3.1.0 and started getting an issue with mappings with the following definition:

.ForAllMembers(o => o.Condition(c =>!c.IsSourceValueNull));这是 以前可以正常运行,因此不会尝试映射 没有源值的属性.升级后, 似乎Automapper面对的目标成员具有 没有匹配的源成员,将尝试从源类型映射到 目标成员.然后,这将引发映射异常,因为 没有针对任何类型的源类型的映射定义 目标属性类型.以前,Automapper似乎 正确地忽略没有匹配的源成员的成员.

.ForAllMembers(o => o.Condition(c => !c.IsSourceValueNull)); This was previously functioning correctly and would not attempt to map properties which did not have a source value. After the upgrade, it seems that Automapper, when faced with a destination member that has no matching source member, will attempt to map from the source type to the destination member. This then throws a mapping exception because there is no mapping definition for the source type to any of the destination property types. Previously, Automapper seemed to rightfully ignore members which did not have a matching source member.

We changed the condition line to:

.ForAllMembers(o => o.Condition(c => c.PropertyMap.SourceMember != null && !c.IsSourceValueNull));

这篇关于如果并非所有源属性都匹配,则AutoMapper无法阻止空源值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆