2014-10-07 218 views
3

我正在使用Automapper將我的模型對象映射到DTO。在DTO中,主鍵應該替換爲相應的對象。爲了這個目的,我用下面的代碼:複雜對象的自動映射器映射

// Model class 
public class SubDepartment 
{ 
    public long Id { get; set; } 
    public string Name { get; set; } 
    public long? DepartmentId { get; set; } 
    public DateTime LastUpdated { get; set; } 
} 

// DTO class 
public class SubDepartmentDTO 
{ 
    public long Id { get; set; } 
    public string Name { get; set; } 
    public Department Department { get; set; } 
    public long EventCount { get; set; } 
} 

// Mapping code 

Mapper.CreateMap<Models.Event.SubDepartment, DTO.SubDepartment>().ForMember(dto => dto.Department, 
       map => map.MapFrom(sd => Mapper.Map<Department, DTO.Department>(_departmentRepository.GetById(sd.DepartmentId.Value)))); 

但是,當我在我的控制器從SUBDEPARTMENT映射到SubDepartmentDTO的「部門」對象始終是零。我嘗試用硬編碼的Department對象替換_departmentRepository.GetById(sd.DepartmentId.Value)代碼,它運行良好。我還驗證了主鍵在數據庫中存在相應的部門。任何人都可以指出我做錯了什麼?

+4

感覺就像你在你的映射器做得太多。它應該在對象之間進行映射,而不是執行數據庫調用。您是否嘗試將數據加載到對象中,然後將該對象映射到dto.department?基本上你會調用兩次地圖,一次是父母,一次是孩子對象。 – JCherryhomes 2014-10-07 11:40:39

回答

0

與此代碼

Mapper.CreateMap<Models.Event.SubDepartment, DTO.SubDepartment>().ForMember(dto => dto.Department,map => map.MapFrom(sd => _departmentRepository.GetById(sd.DepartmentId.Value))); 

嘗試它,如果它不工作,你可以嘗試自定義值解析器

Models.Event.SubDepartment, DTO.SubDepartment>().ForMember(dto => dto.Department, map => map.ResolveUsing<DepartmentResolver>()); 

public class DepartmentResolver: ValueResolver<Models.Event.SubDepartment,DTO.SubDepartment> 
{ 
    Reporsitory _departmentRepository; 
    protected override DTO.SubDepartment ResolveCore(Models.Event.SubDepartment source) 
    { 
     return _departmentRepository.GetById(source.DepartmentId.Value); 
    } 
}