c# - 当 source 上的属性为 false 时是否可以映射到 null?

标签 c# .net automapper

我正在定义源类和目标类之间的映射:

Mapper.CreateMap<Source, Target>();

如果 Source 上的某个属性设置为特定值,我希望映射返回 null:

// If Source.IsValid = false I want the mapping to return null
Source s = new Source { IsValid = false };
Target t = Mapper.Map<Target>(s);
Assert.IsNull(t);

如何配置 AutoMapper 来实现这一点?

最佳答案

您可以这样定义您的映射:

Mapper.CreateMap<Source, Target>().TypeMap
  .SetCondition(r => ((Source)r.SourceValue).IsValid);

关于c# - 当 source 上的属性为 false 时是否可以映射到 null?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31016357/

相关文章:

linq - 如何从 Expression<Func<DomainType>> 谓词转换为 Expression<Func<DTOtype> 谓词

c# - 是否可以自动创建自动映射器映射?

c# - 如何将 VB.NET 语言支持添加到 C# web api Controller

c# - TryGetValue - 传递未初始化的值好吗?

c# - 在 C# 中自动完成文本框

c# - 如何以单独的形式等待按钮事件

c# - .NET 导出到 excel - 不显示子行

c# - AutoMapper MapFrom 没有效果

c# - 使用 Entity Framework 添加和更新实体

c# - 如何重构重载方法