AutoMapper:处理空图像(映射到 byte[] 中的 null 但不是其他集合)

AutoMapper: Working with empty images (map to null in byte[] but not other collections)

在 AutoMapper 中,集合的一般概念是它们永远不应该为空。这是有道理的,但是在处理图像之类的东西时我该如何管理呢?在 C# 中保存为 byte[] 的图像不能是空数组,而它应该是 null。我不想使用 AllowNullCollections 配置设置来更改所有集合的默认行为。我只想 byte[]null 映射到 null

我目前正在使用 AutoMapper 8。


示例代码和我的尝试

实体

public class SourceClass
{
    public int Id { get; set; }
    public byte[] Image1 { get; set; }
    public byte[] Image2 { get; set; }
    public byte[] Image3 { get; set; }
    public List<SourceChildClass> Children { get; set; }
}

public class SourceChildClass
{
    public string Test { get; set; }
}

public class DestinationClass
{
    public int Id { get; set; }
    public byte[] Image1 { get; set; }
    public byte[] Image2 { get; set; }
    public byte[] Image3 { get; set; }
    public List<DestinationChildClass> Children { get; set; }
}

public class DestinationChildClass
{
    public string Test { get; set; }
}

映射

CreateMap<SourceClass, DestinationClass>()
    // .ForMember(dest => dest.Image1, ... default behaviour ...)
    .ForMember(dest => dest.Image2, opts => opts.AllowNull()) // does not work
    .ForMember(dest => dest.Image3, opts => opts.NullSubstitute(null)); // does not work

CreateMap<SourceChildClass, DestinationChildClass>();

测试代码

var sourceEmpty = new SourceClass
{
    Id = 1,
};

// I want the byte[] images to map to null,
// but "Children" should map to an empty list, as per the default behavour.
var destinationEmpty = Mapper.Map<SourceClass, DestinationClass>(sourceEmpty);

你试过值转换器吗?您可以将其应用于会员。 https://docs.automapper.org/en/stable/Value-transformers.html

这个问题我目前有两个答案。

  1. 根据具体情况,使用After Map

    CreateMap<SourceClass, DestinationClass>()
        .AfterMap((src, dest) => { if (src.Image == null) dest.Image = null; });
    
  2. 在更全球化的范围内,使用 value transformer

    cfg.ValueTransformers.Add<byte[]>(val => val.Length == 0 ? null : val);