AutoMapper。使用空图像(在byte[]中映射为null,而不是其他集合)。

问题描述 投票:0回答:1

在 AutoMapper 中,集合的一般概念是它们永远不应该是空的。这是有道理的,但是当我处理图像这样的东西时,我该如何管理呢?图片,在C#中被保存为 byte[],不能是空数组,而应该是 null. 我不想使用类似 AllowNullCollections 配置设置来改变所有集合的默认行为。我只想 byte[] 绘制 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);
c# automapper
1个回答
1
投票

你试过值变换器吗?你可以把这个应用到成员上。https:/docs.automapper.orgenstableValue-transformers.html。


0
投票

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

  1. 根据具体情况,使用的是 地图后.

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

    cfg.ValueTransformers.Add<byte[]>(val => val.Length == 0 ? null : val);
    
© www.soinside.com 2019 - 2024. All rights reserved.