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