Automapper - 如何映射到构造函数参数而不是属性设置器 [英] Automapper - how to map to constructor parameters instead of property setters
问题描述
如果我的目标 setter 是私有的,我可能想使用目标对象的构造函数映射到对象.您将如何使用 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?
推荐答案
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.
另请注意,这与 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屋!