2012-10-16 58 views
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 }; 
    } 
} 

回答

8

可以使用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 
+1

因爲我將Automapper的所有配置放在不同的位置,所以我不想在轉換之前創建新的地圖。離子就是我需要的。謝謝您的回答。 – Andris