Automapper-如何映射到构造函数参数而不是属性设置器 [英] Automapper - how to map to constructor parameters instead of property setters

查看:221
本文介绍了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; }
    }
}

这篇关于Automapper-如何映射到构造函数参数而不是属性设置器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆