【发布时间】:2018-02-16 07:28:45
【问题描述】:
我正在使用AutoMapper 将 ViewModel 映射到 Model。但是,如果相应的源属性是null,我希望不映射属性。
我的源码类如下:
public class Source
{
//Other fields...
public string Id { get; set; } //This should not be mapped if null
}
目标类是:
public class Destination
{
//Other fields...
public Guid Id { get; set; }
}
这是我配置映射器的方式:
Mapper.Initialize(cfg =>
{
//Other mappings...
cfg.CreateMap<Source, Destination>()
.ForAllMembers(opts => opts.Condition((src, dest, srcMember) => srcMember != null));
});
我认为映射意味着如果源属性是null,则不会在目标中覆盖属性。但显然我错了:即使Source.Id 为空,它仍然会被映射,AutoMapper 为其分配一个空的 Guid (00000000-0000-0000-0000-000000000000),覆盖现有的。如果源为空,如何正确告诉 AutoMapper 跳过属性映射?
注意:我不认为这是Guid<->String 转换的问题,这种转换在automapper 中有效,我在pass 中使用过。问题是当它为空时它不会跳过 Id 属性。
【问题讨论】:
标签: c# automapper