[英]AutoMapper: Working with empty images (map to null in byte[] but not other collections)
在 AutoMapper 中,collections 的一般概念是它们永远不应该是 null。 这是有道理的,但是在处理图像之类的东西时,我该如何管理呢? 图像,作为byte[]
保存在 C# 中,当它应该是null
时不能是空数组。 我不想使用类似AllowNullCollections
配置设置来更改所有 collections 的默认行为。 我只想要byte[]
到 map 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.