AutoMapper是否有更简洁的方法将空转换为空GUID而不是显式CreateMap?

时间:2012-04-08 16:37:39

标签: c# .net automapper

我的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);

1 个答案:

答案 0 :(得分:1)

创建自定义类型转换器。

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>();