如何使用Automapper将所有零int值映射到可为空的int目标的空值?

时间:2013-01-10 13:51:02

标签: asp.net-mvc model-view-controller asp.net-mvc-4 automapper

我将int?用于我所需要的所有' FK' ViewModels中的属性。这为我提供了一种在Create视图模型上指定值可为空的简单方法,并且必须为其分配一个值以满足Required属性。

我的问题来自于我首先使用域工厂创建域模型实体,然后将其映射到视图模型。现在,视图模型中的许多可为空的int在域模型中从非可空的int中赋值为0。我宁愿不在视图模型中构建新实体,只将其映射回域模型以避免他的。我还可以做些什么?我确定有一个可以帮助我的自动神像伏都教。

2 个答案:

答案 0 :(得分:1)

编辑:你不需要做任何这些,但我想我会留在这里寻找类似解决方案的人。你要做的就是提供从intint?的映射,如下所示:Mapper.Map<int, int?>()

在这种情况下,我相信您可以使用自定义类型转换器,它继承自自动化器ITypeConverter。这段代码有效,我通过.NET Fiddle运行它:

using System;
using AutoMapper;

public class Program
{
    public void Main()
    {
        CreateMappings();
        var vm = Mapper.Map<MyThingWithInt, MyThingWithNullInt>(new MyThingWithInt());

        if (vm.intProp.HasValue)
        {
            Console.WriteLine("Value is not NULL!");

        }
        else
        {
            Console.WriteLine("Value is NULL!");
        }
    }

    public void CreateMappings() 
    {
        Mapper.CreateMap<int, int?>().ConvertUsing(new ZeroToNullIntTypeConverter ());
        Mapper.CreateMap<MyThingWithInt, MyThingWithNullInt>();
    }


    public class ZeroToNullIntTypeConverter : ITypeConverter<int, int?>
    {
        public int? Convert(ResolutionContext ctx)
        {
           if((int)ctx.SourceValue == 0)
           {
              return null;
           }
            else
           {
               return (int)ctx.SourceValue;
           }
        }
    }

    public class MyThingWithInt
    {
        public int intProp = 0; 
    }

    public class MyThingWithNullInt
    {
        public int? intProp {get;set;}  
    }
}

答案 1 :(得分:0)

您始终可以在映射中使用.ForMember()方法。像这样:

Mapper
    .CreateMap<Entity, EntityDto>()
    .ForMember(
        dest => dest.MyNullableIntProperty,
        opt => opt.MapFrom(src => 0)
    );
相关问题