我使用自动映射器。我有两个类:具有单一属性的 TypeA;TypeB 具有两个属性,其中一个具有私有 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 };
}
}