2012-10-16 13 views
5

Tôi sử dụng Automapper. Tôi có hai lớp: TypeA với một thuộc tính duy nhất; TypeB với hai thuộc tính, một trong số chúng có setter và giá trị riêng cho thuộc tính này được truyền qua constructor. TypeB không có hàm tạo mặc định.Làm cách nào để chuyển giá trị ngữ cảnh sang Bản đồ Automapper?

Câu hỏi: có thể định cấu hình Automapper để chuyển đổi TypeA thành TypeB hay không.

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 }; 
    } 
} 

Trả lời

8

Bạn có thể sử dụng một trong những ConstructUsing định nghĩa chồng nói AutoMapper mà constructor nó nên sử dụng

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 

Là một giải pháp thay thế, bạn có thể tạo TypeB của bạn bằng tay AutoMapper có thể điền vào phần còn lại của các thuộc tính ":

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

Vì tôi có tất cả cấu hình của Automapper ở vị trí riêng biệt, tôi không muốn tạo Maps mới trước khi chuyển đổi. ion là những gì tôi cần. Cảm ơn bạn vì câu trả lời. – Andris