【问题标题】:Can't use AutoMapper to map to null value无法使用 AutoMapper 映射到空值
【发布时间】:2020-01-20 10:31:05
【问题描述】:
public class TestNullableString {
    public string? Test;

    public TestNullableString(string? test) {
        Test = test;
    }
}

public class TestNonNullableString {
    public string Test;
}

public class TestProfile : Profile
{
    public TestProfile() {
        CreateMap<TestNonNullableString, TestNullableString>
             .ForMember(dest => dest.Test, opt => {
                 opt.AllowNull();
                 opt.MapFrom(src => src.Test == "" ? null : src.Test);
              });
    }
}

如果我尝试从 NonNullableString 映射到 NullableString,它仍然会在映射时为我提供空字符串。它不会给我一个空值,即使 NonNullableString 是“”。我做错了什么?

我正在使用 AutoMapper 9.0.0。

PS。我也尝试将 AllowNullDestinationValues 设置为 true,但没有成功。

【问题讨论】:

  • 我意识到我复制的代码太少了。我现在已经在 TestNullableString 中添加了构造函数,这现在不适用于您建议的解决方案。

标签: c# .net .net-core automapper


【解决方案1】:
CreateMap<TestNonNullableString, TestNullableString>()
            .ForMember(dest => dest.Test,
                opt => { opt.MapFrom(src => string.IsNullOrWhiteSpace(src.Test) ? null : src.Test); })
            .ConstructUsing(x => new TestNullableString(string.IsNullOrWhiteSpace(x.Test) ? null: x.Test ));

【讨论】:

  • 这行得通(我也刚找到)。这个解决方案并没有给我留下深刻的印象,但我猜 AutoMapper 对 Nullables 来说不太好。 (希望我可以先订购构造,然后再订购 MapFrom)
猜你喜欢
  • 2011-02-08
  • 2011-01-12
  • 1970-01-01
  • 2013-08-12
  • 2020-05-19
  • 2023-01-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多