代码之家  ›  专栏  ›  技术社区  ›  pellea

AutoMapper Map()返回错误的值

  •  2
  • pellea  · 技术社区  · 9 年前

    我有一个类的映射 MyClass 同班同学 类名 .

    该类有一个 List<T> 属性。 这个 列表<T> 在映射之前为NULL。

    与映射后 自动映射器 这个 列表<T> 不再为空。( AllowNullDestinationValues 在这里什么都不做…)

    这是故意的还是bug?我是否错过了一些配置步骤?

    using System.Collections.Generic;
    using System.Diagnostics;
    using AutoMapper;
    
    namespace ConsoleApplication1
    {
        public class MyClass
        {
            public string Label { get; set; }
    
            public List<int> Numbers { get; set; }
        }
    
        class Program
        {
            static void Main(string[] args)
            {
                Mapper.CreateMap<MyClass, MyClass>();
                MyClass obj1 = new MyClass { Label = "AutoMapper Test" };
                MyClass obj2 = new MyClass();
                Mapper.Map(obj1, obj2);
    
                Debug.Assert(obj2 != null && obj2.Numbers == null, "FAILED");
            }
        }
    }
    

    我使用NuGet的AutoMapper v4.1.1。

    1 回复  |  直到 9 年前
        1
  •  2
  •   Will Ray    9 年前

    默认情况下,AutoMapper会将空集合映射为空集合。您可以通过创建自己的AutoMapper配置文件来进行配置。

    看看下面的代码。

    public class MyClass
    {
        public string Label { get; set; }
    
        public List<int> Numbers { get; set; }
    }
    class Program
    {
        static void Main(string[] args)
        {
            Mapper.AddProfile<MyProfile>(); // add the profile
            MyClass obj1 = new MyClass { Label = "AutoMapper Test" };
            MyClass obj2 = new MyClass();
            Mapper.Map(obj1, obj2);
    
            Debug.Assert(obj2 != null && obj2.Numbers == null, "FAILED");
        }
    }
    
    public class MyProfile : Profile
    {
        protected override void Configure()
        {
            AllowNullCollections = true;
            CreateMap<MyClass, MyClass>();
            // add other maps here.
        }
    }