自动映射器将数组属性设置为零长度数组,而不是null [英] Automapper sets an array property to a zero-length array rather than null

查看:95
本文介绍了自动映射器将数组属性设置为零长度数组,而不是null的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Automapper将值从一个实例复制到另一个实例,并且我发现如果类具有数组属性,并且源实例的属性设置为null,则Automapper会将目标属性设置为一个零长度的数组,而不是我期望的null.

I'm using Automapper to copy values from one instance to another, and I'm finding that if the class has an array property, and the source instance has the property set to null, Automapper sets the destination property to a zero-length array instead of null as I expected.

是否有一种方法可以配置Automapper,以在源为null时将目标设置为null?

Is there a way to configure Automapper to set the destination to null when the source is null?

如果我的解释不清楚,下面的代码说明了我要描述的内容:

In case my explanation is unclear, the following code illustrates what I'm trying to describe:

public class Test
{
    public byte[] ByteArray { get; set; }
    public int? NullableInt { get; set; }
    public int Int { get; set; }
}

class Program
{
    static void Main(string[] args)
    {
        Mapper.CreateMap<Test, Test>();

        var test1 = new Test { Int = 123, NullableInt = null, ByteArray = null };
        var test2 = Mapper.Map<Test>(test1);

        // test1:  Int == 123, NullableInt == null, ByteArray == null
        // test2:  Int == 123, NullableInt == null, ByteArray == byte[0]  <-- expect this to be null
    }
}

推荐答案

我发现这已经被报告为问题,并添加了新的配置选项(请参见 commit ).目前,该选项不在通过NuGet发行的版本中,但是我能够找到一种方法来解决此问题,直到发行下一个版本:

I found that this was already reported as an issue, and a new configuration option was added (see this commit). At this time, the option is not in the release available via NuGet, but I was able to figure out a way to handle this until the next version is released:

Mapper.CreateMap<Test, Test>()
    .ForMember(t => t.ByteArray, opt => opt.ResolveUsing(t => t.ByteArray == null ? null : t.ByteArray));


更新:


Update:

从2.1.265.0版开始,您可以使用AllowNullCollections属性:

As of version 2.1.265.0, you can using the AllowNullCollections property:

Mapper.Configuration.AllowNullCollections = true;
Mapper.CreateMap<Test, Test>();

这篇关于自动映射器将数组属性设置为零长度数组,而不是null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆