2017-02-28 325 views
1

我具有以下的類結構Automapper映射嵌套對象

public class ClassA 
{ 
    public ClassB objB; 
} 

Public class ClassB 
{ 
    public ListOfData objListofData; 
} 

public class ListOfData 
{ 
    public Employee objEmp; 
} 

public class Employee 
{ 
    public string FirstName; 
    public string LastName; 
} 

上述層次結構的返回類型將是

"ClassA":{ 
    "classB":{ 
     "ListOfData":{ 
      "employee":{ 
       "FirstName":"David", 
       "LastName" :"Peter" 
      } 
     } 
    } 
} 

我要地圖僱員類EmployeeViewModel其中僱員名字和姓氏將被映射到employeeViewModel FullName屬性。我可以通過下面的代碼段

public class EmployeeViewModel 
{ 
    public FullName; 
} 


CreateMap<Employee,EmployeeViewModel>() 
         .ForMember(dest => dest.FullName, 
            opts => opts.MapFrom(
             src => string.Format("{0} {1}", 
             src.FirstName, src.LastName))); 

現在怎麼辦就回國了具有EmployeeViewModel的映射原始ClassA的對象實現這一目標。像這樣?

"ClassA":{ 
    "classB":{ 
     "ListOfData":{ 
      "EmployeeViewModel":{ 
       "FullName":"David Peter" 
      } 
     } 
    } 
} 

回答

1

花時間閱讀文檔的量好後,我發現這裏的解決方案是我的做法

一)創建類源&目的地類這樣

public class ClassA 
{ 
    public ClassB objB; 
} 

Public class ClassB 
{ 
    public ListOfData objListofData; 
} 

public class ListOfData 
{ 
    public Employee objEmp; 
} 

public class Employee 
{ 
    public string FirstName; 
    public string LastName; 
} 
------------------------------------ 
public class DestClassA 
{ 
    public DestClassB objB; 
} 

Public class DestClassB 
{ 
    public DestListOfData objListofData; 
} 

public class DestListOfData 
{ 
    public DestEmployee objEmp; 
} 

public class EmployeeViewModel 
{ 
    public string FullName; 
} 

二)創建映射

var config = new MapperConfiguration(cfg => { 

    cfg.CreateMap<Employee, EmployeeViewModel>(). 
       ForMember(dest => dest.FullName, opts => opts.MapFrom(
        src => string.Format("{0} - {1}", 
        src.FirstName, src.LastName))); 
    cfg.CreateMap<ListOfData, DestListOfData>(); 
    cfg.CreateMap<GetFundFamilyOutOfBalanceTotalsResponse, GetFundFamilyOutOfBalanceTotalsResponseMapped>(); 
    cfg.CreateMap<ClassB, DestClassB>(); 
    cfg.CreateMap<ClassA, DestClassA>(); 
}); 

//這是爲了確保你的映射是正確的牛逼

config.AssertConfigurationIsValid(); 

//你可以測試是否有望反對由automapper創建映射之後添加以下代碼

var mapper = config.CreateMapper(); 
var output = new ClassA 
{ 
    objClassB = new ClassB 
    { 
     objListofData = new ListOfData 
     { 
      Employee = new [] 
       { 
        new Employee { FirstName = "David", LastName ="Peter" } 
       } 
     } 
    } 
}; 

var destMap = mapper.Map<DestClassA>(output); 

//如果你探索這個對象,你會發現這樣的

對象struture
"ClassA":{ 
    "classB":{ 
     "ListOfData":{ 
      "EmployeeViewModel":{ 
       "FullName":"David Peter" 
      } 
     } 
    } 
}