tags:

views:

365

answers:

1

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?

+8  A: 

Use 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.

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; }
    }
}
Jon Erickson
I'm guessing "ConstructUsing" must be in a newer version of automapper than the one we're using. Thanks Jon
jlembke

related questions