简体   繁体   English

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

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

In AutoMapper, the general concept for collections is that they should never be null.在 AutoMapper 中,collections 的一般概念是它们永远不应该是 null。 This makes sense, but how do I manage this when working with things like images?这是有道理的,但是在处理图像之类的东西时,我该如何管理呢? Images, kept in C# as byte[] , must not be an empty array when it should be null .图像,作为byte[]保存在 C# 中,当它应该是null时不能是空数组。 I do not want to use something like the AllowNullCollections configuration setting to change the default behaviour for all collections.我不想使用类似AllowNullCollections配置设置来更改所有 collections 的默认行为。 I only want byte[] to map null to null .我只想要byte[]到 map nullnull

I'm currently using AutoMapper 8.我目前正在使用 AutoMapper 8。


Sample code & what I tried示例代码和我尝试过的

The entities实体

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; }
}

The mapping映射

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>();

The test code测试代码

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);

Have you tried value transformers?你试过价值转换器吗? You can apply this to a member.您可以将此应用于成员。 https://docs.automapper.org/en/stable/Value-transformers.html https://docs.automapper.org/en/stable/Value-transformers.html

I currently have two answers to this question.我目前对这个问题有两个答案。

  1. On a case-by-case basis, using After Map .根据具体情况,使用After Map

     CreateMap<SourceClass, DestinationClass>().AfterMap((src, dest) => { if (src.Image == null) dest.Image = null; });
  2. On a more global scale, using a value transformer .在更全球范围内, 使用价值转换器。

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

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

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