Automapper-如何映射到构造函数参数而不是属性设置器

Automapper-如何映射到构造函数参数而不是属性设置器

问题描述:

在我的目标设置器是私有的情况下,我可能想使用目标对象的构造函数映射到该对象.您将如何使用Automapper做到这一点?

In cases where my destination setters are private, I might want to map to the object using the destination object's constructor. How would you do this using Automapper?

使用ConstructUsing

这将允许您指定在映射过程中使用哪个构造函数.但是所有其他属性都将根据约定自动映射.

this will allow you to specify which constructor to use during the mapping. but then all of the other properties will be automatically mapped according to the conventions.

还请注意,这与ConvertUsing的不同之处在于,convert using将不会继续通过约定进行映射,而是可以完全控制映射.

Also note that this is different from ConvertUsing in that convert using will not continue to map via the conventions, it will instead give you full control of the mapping.

Mapper.CreateMap<ObjectFrom, ObjectTo>()
    .ConstructUsing(x => new ObjectTo(arg0, arg1, etc));

...

using AutoMapper;
using NUnit.Framework;

namespace UnitTests
{
    [TestFixture]
    public class Tester
    {
        [Test]
        public void Test_ConstructUsing()
        {
            Mapper.CreateMap<ObjectFrom, ObjectTo>()
                .ConstructUsing(x => new ObjectTo(x.Name));

            var from = new ObjectFrom { Name = "Jon", Age = 25 };

            ObjectTo to = Mapper.Map<ObjectFrom, ObjectTo>(from);

            Assert.That(to.Name, Is.EqualTo(from.Name));
            Assert.That(to.Age, Is.EqualTo(from.Age));
        }
    }

    public class ObjectFrom
    {
        public string Name { get; set; }
        public int Age { get; set; }
    }

    public class ObjectTo
    {
        private readonly string _name;

        public ObjectTo(string name)
        {
            _name = name;
        }

        public string Name
        {
            get { return _name; }
        }

        public int Age { get; set; }
    }
}