繁体   English   中英

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

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

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

我目前正在使用 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. 在更全球范围内, 使用价值转换器。

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

暂无
暂无

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

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