简体   繁体   中英

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. 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 . I do not want to use something like the AllowNullCollections configuration setting to change the default behaviour for all collections. I only want byte[] to map null to null .

I'm currently using 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

I currently have two answers to this question.

  1. On a case-by-case basis, using 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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