有没有比显式创建映射更整洁的方法让自动映射器从空 GUID 转换为空 GUID
本文关键字:映射 GUID 转换 创建 有没有 方法 | 更新日期: 2023-09-27 18:30:21
我的 Code First 数据模型中有几个不可为空的 GUID 属性,这些属性映射到视图模型中的Guid?
。我对空的 GUID(全为零)没有用处,所以我使用以下映射,但我不禁想知道是否有更整洁的方法?AutoMapper配置的未知深度需要我花费数年时间才能自己探索。
Mapper.CreateMap<Guid, Guid?>().ConvertUsing(guid => guid == Guid.Empty ? (Guid?)null : guid);
Mapper.CreateMap<Guid?, Guid>().ConvertUsing(guid => !guid.HasValue ? Guid.Empty : guid.Value);
创建自定义类型转换器。
https://github.com/AutoMapper/AutoMapper/wiki/Custom-type-converters
public class NullableByteToNullableIntConverter : ITypeConverter<Byte?, Int32?>
{
public Int32? Convert(ResolutionContext context)
{
return context.IsSourceValueNull ? (int?) null : System.Convert.ToInt32(context.SourceValue);
}
}
然后:
Mapper.CreateMap<byte?, int?>().ConvertUsing<NullableByteToNullableIntConverter>();