我使用 Automapper。 我有两个类:具有单一属性的 TypeA;具有两个属性的 TypeB,其中一个具有私有(private) setter ,并且此属性的值通过构造函数传递。 TypeB 没有默认构造函数。
问题:是否可以配置 Automapper 将 TypeA 转换为 TypeB。
public class TypeA
{
public string Property1 { get; set; }
}
public class TypeB
{
public TypeB(int contextId)
{ ContextId = contextId; }
public string Property1 { get; set; }
public int ContextId { get; private set; }
}
public class Context
{
private int _id;
public void SomeMethod()
{
TypeA instanceOfA = new TypeA() { Property1 = "Some string" };
// How to configure Automapper so, that it uses constructor of TypeB
// and passes "_id" field value into this constructor?
// Not work, since "contextId" must be passed to constructor of TypeB
TypeB instanceOfB = Mapper.Map<TypeB>(instanceOfA);
// Goal is to create folowing object
instanceOfB = new TypeB(_id) { Property1 = instanceOfA.Property1 };
}
}
最佳答案
您可以使用 ConstructUsing
重载之一来告诉 AutoMapper 它应该使用哪个构造函数
TypeA instanceOfA = new TypeA() { Property1 = "Some string" };
_id = 3;
Mapper.CreateMap<TypeA, TypeB>().ConstructUsing((TypeA a) => new TypeB(_id));
TypeB instanceOfB = Mapper.Map<TypeB>(instanceOfA);
// instanceOfB.Property1 will be "Some string"
// instanceOfB.ContextId will be 3
作为替代解决方案,您可以手动创建 TypeB
,AutoMapper 可以填写其余属性”:
TypeA instanceOfA = new TypeA() { Property1 = "Some string" };
_id = 3;
Mapper.CreateMap<TypeA, TypeB>();
TypeB instanceOfB = new TypeB(_id);
Mapper.Map<TypeA, TypeB>(instanceOfA, instanceOfB);
// instanceOfB.Property1 will be "Some string"
// instanceOfB.ContextId will be 3
关于c# - 如何将上下文值传递给 Automapper Map?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12908476/