【问题标题】:AutoMapper is mapping false for an optional bool even when the optional bool is nullAutoMapper 为可选 bool 映射 false,即使可选 bool 为 null
【发布时间】:2020-11-04 17:47:46
【问题描述】:

我对我的应用程序中的代码 sn-p 有疑问。 x.UsesFeature 和 Person.UsesFeature 都是可选 bool 类型(bool?)。当 src.Person.UsesFeature = null 时,将评估三元运算符的右侧。我的理解是bool的默认值?一片空白。但是当完成映射时,x.UsesFeature 设置为 False,而不是 null。为什么会这样?

                var config = new MapperConfiguration(cfg => cfg.AddProfile<TestProfile>());

。 . .then 当我映射该 TestProfile 类中的属性时

   .ForMember(x => x.UsesFeature, opt =>
            {
                opt.MapFrom(src => src.User.UsesFeature.HasValue ? src.User.UsesFeature.Value : default);
            })

【问题讨论】:

标签: c# automapper


【解决方案1】:

这不是 Automapper 的问题,如果您执行以下操作,您会看到它设置为 false

bool? foo = null;
var bar = foo.HasValue ? foo.Value : default;

但是,只需将默认值更改为 default(bool?) 即可解决您的问题。

bool? foo = null;
var bar = foo.HasValue ? foo.Value : default(bool?);

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-07-20
  • 2017-02-03
  • 2012-08-24
  • 1970-01-01
  • 2017-10-10
相关资源
最近更新 更多