【问题标题】:How can I use Automapper to map all zero int values to null values for nullable int targets?如何使用 Automapper 将所有零 int 值映射到可为空 int 目标的空值?
【发布时间】:2013-01-10 13:51:01
【问题描述】:

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

我的问题出现了,因为我首先使用域工厂创建域模型实体,然后将其映射到视图模型。现在,视图模型中的许多可空整数从域模型中的不可空整数中分配为 0。我不希望在视图模型中构建新实体,而只将其映射回域模型以避免他的。我还可以做些什么?我确定有 som Automapper voodoo 可以帮助我。

【问题讨论】:

  • 不完全确定你想要什么,但看看 IgnoreAllowNullDestinationValues 映射指令。这可能会给你你所需要的。
  • 我尝试了一个快速示例,Automapper 似乎可以很好地将空引用类型映射到可空整数(将空分配给可空整数)。您能否展示一些无法按您希望的方式运行的示例代码?
  • @PatrickSteele 我的问题是我只希望映射到用于创建新实体的视图模型,而不是用于编辑实体的模型。通过编辑,如果 int 为零,我想将其保持为零而不是将其归零。
  • 等等...你刚才说的与问题的标题完全相反。您的问题是“将所有零 int 值映射为 null”,但您的评论只是说“我想将其保持为零而不是使其归零”。抱歉,我不清楚您需要什么——您有什么办法可以提供一些示例代码吗?
  • @PatrickSteele 我试图在我的问题中解释这仅用于创建操作。

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


【解决方案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;}  
    }
}

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 是的,但这仅对一个映射有效。我正在寻找一个通用的解决方案,比如ForMemberOfType&lt;T&gt;
    猜你喜欢
    • 2016-01-22
    • 1970-01-01
    • 2017-06-17
    • 2011-01-12
    • 2023-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-19
    相关资源
    最近更新 更多