简体   繁体   English

Automapper 和处理空属性

[英]Automapper and dealing with null properties

I've set my mapping up as follows:我已经设置了我的映射如下:

CreateMap<SourceClass, DestinationClass>().ForMember(destinationMember => destinationMember.Provider,
                memberOptions => memberOptions.MapFrom(src => src.Providers.FirstOrDefault()));

Where I'm mapping from a List in my SourceClass to a string in my destination class.我从 SourceClass 中的 List 映射到目标类中的字符串。

My question is, how can I handle the case where "Providers" is null?我的问题是,如何处理“Providers”为空的情况?

I've tried using:我试过使用:

src?.Providers?.FirstOrDefault()

but I get an error saying I can't use null propagators in a lambda.但是我收到一条错误消息,说我不能在 lambda 中使用空传播器。

I've been reading up on Automapper and am still unsure if AM automatically handles the null case or not.我一直在阅读 Automapper,但仍然不确定 AM 是否会自动处理 null 情况。 I tried to build the expression tree, but was not able to see any information that provided additional informations.我尝试构建表达式树,但无法看到任何提供附加信息的信息。

If it helps, I'm using automapper v 6.1.1.如果有帮助,我正在使用 automapper v 6.1.1。

You could try using a ValueConverter with AutoMapper.您可以尝试将ValueConverter与 AutoMapper一起使用。 That might look something like this这可能看起来像这样

public class ListFormatter : IValueConverter<string, List<string>>
{
  public List<string> Convert(string source)
  {
    if (source != null)
    {
      return new List<string> { source };
    }
    return new List<string>();
  }
}

And then you can use it like this然后你可以像这样使用它

CreateMap<SourceClass, DestinationClass>()
  .ForMember(destinationMember => destinationMember.Provider,
             memberOptions => memberOptions.ConvertUsing(new ListFormatter()));

This would allow you to change your value converter in the future if you need to switch logic or do something more complex.如果您需要切换逻辑或做一些更复杂的事情,这将允许您在未来更改您的价值转换器。

Edit编辑

Since you are using an older version, you could use a private/static/extension method to do the same thing.由于您使用的是旧版本,因此您可以使用私有/静态/扩展方法来做同样的事情。 So something like所以像

List<string> ConvertStringToList(string source)
{
  if (source != null)
  {
    return new List<string> { source };
  }
  return new List<string>();
}

and then call it like so然后像这样称呼它

CreateMap<SourceClass, DestinationClass>()
  .ForMember(destinationMember => destinationMember.Provider,
             memberOptions => memberOptions.MapFrom(src => ConvertStringToList(src.Provider)));

I generally prefer this to doing something inline as things get more complex, for the sake of readability为了可读性,当事情变得更复杂时,我通常更喜欢这样做而不是内联

尝试使用 AutoMapper 中的 NullSubstitution 选项,您可以在此处阅读

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

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