简体   繁体   English

AutoMapper-将目标字符串设置为null实际上使它成为string.Empty

[英]AutoMapper - setting destination string to null actually makes it string.Empty

With the following mapping: 使用以下映射:

Mapper.CreateMap<ObjectA, ObjectB>()
    .ForMember(dest => dest.SomeStringProperty, opt => opt.MapFrom(src => null))

SomeStringProperty is now empty string not null (as I would expect) SomeStringProperty现在是空字符串,而不是null(正如我期望的那样)

Is this a bug? 这是错误吗? How can I get it to actually be null? 我怎样才能使它实际上为空?

I see that opt.Ignore() will make it null but I actually want to do a conditional null like the following and the above simplified bug(?) is preventing this 我看到opt.Ignore()将其设置为null,但实际上我想像下面这样执行条件null,而上述简化的bug(?)可以防止这种情况发生

Mapper.CreateMap<ObjectA, ObjectB>()
    .ForMember(dest => dest.SomeStringProperty, opt => opt.MapFrom(src => src.SomeOtherProp != null ? src.SomeOtherProp.Prop1 : null))

I found the setting after looking through the source code... Confirming that this is not a bug, but in fact a configurable setting. 在查看源代码后,我找到了该设置。。。确认这不是错误,而是实际上是可配置的设置。

When I configure my mappings.. 当我配置映射时

Mapper.Initialize(x =>
{
    x.AddProfile<UIProfile>();
    x.AddProfile<InfrastructureProfile>();
    x.AllowNullDestinationValues = true; // does exactly what it says (false by default)
});

you could define map for strings using 您可以使用以下方式为字符串定义映射

ITypeConverter<string, string>

and when you convert return null if null. 转换时,如果为null,则返回null。 I think it is by design that you get an empty string and I even find this natural and useful myself but I may of course be wrong ;) 我认为这是设计使您得到的空字符串,我自己也觉得这很自然和有用,但我当然可能错了;)

I can provide more precise code than above upon request but reckon you know what you're doing. 我可以根据要求提供比上面更精确的代码,但我想您知道自己在做什么。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM