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