5
我使用Automapper。 我有兩個類:TypeA與單個屬性; TypeB具有兩個屬性,其中一個具有私有setter,並且此屬性的值通過構造函數傳遞。 TypeB沒有默認的構造函數。如何將上下文值傳遞給Automapper Map?
問題:是否可以配置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 };
}
}
因爲我將Automapper的所有配置放在不同的位置,所以我不想在轉換之前創建新的地圖。離子就是我需要的。謝謝您的回答。 – Andris