2017-07-11 173 views
0

我正在嘗試使用automapper映射嵌套集合,並且我已經完成了基本設置和配置。當我嘗試執行映射時,嵌套值將爲空。我試圖追隨幾個帖子,把一些東西放在一起。我希望列表具有層次結構而不是展平。任何對此的幫助都會很大。Automapper中的嵌套集合映射

源實體:

public class OuterEntity 
{ 
    public int ID { get; set; } 
    public string Name { get; set; } 
    public List<InnerEntity> InnerEntityList { get; set; } 
} 

public class InnerEntity 
{ 
    public int InnerId { get; set; } 
    public string InnerName { get; set; } 
    public List<InnerMostEntity> InnerMostList { get; set; } 
} 

public class InnerMostEntity 
{ 
    public int InnerMostId { get; set; } 
    public string InnerMostName { get; set; } 
    public DateTime ModifiedDate { get; set; } 
} 

目的實體:

public class OuterEntityDTO 
{ 
    public int ID { get; set; } 
    public string Name { get; set; } 
    public List<InnerEntity> InnerEntityList { get; set; } 
} 

public class InnerEntityDTO 
{ 
    public int InnerId { get; set; } 
    public string InnerName { get; set; } 
    public List<InnerMostEntity> InnerMostList { get; set; } 
} 

public class InnerMostEntityDTO 
{ 
    public int InnerMostId { get; set; } 
    public string InnerMostName { get; set; } 
    public DateTime ModifiedDate { get; set; } 
} 

控制器類:

public List<OuterEntityDTO> GetAll() 
{ 

var outerEntityList = myRepo.GetAll(); //Type of List<OuterEntity> 

var config = new MapperConfiguration(cfg => 
{ 
    cfg.CreateMap<OuterEntity, OuterEntityDTO>().ReverseMap(); 
    cfg.CreateMap<InnerEntity, InnerEntityDTO>().ReverseMap(); 
    cfg.CreateMap<InnerMostEntity, InnerMostEntityDTO>().ReveseMap(); 
}); 

config.AssertConfigurationIsValid(); 

var innerMostDTO = Mapper.Map<List<OuterEntity>,List<OuterEntityDTO>>(outerEntityList); 

//The inner list at first level itself is null. 
return innerMostDTO; 
} 

我試圖在DOT NET Core中實現這一點。 Autommaper版本6.1.1

+0

是源對象填充(延遲加載)? –

+0

是源對象被填充。不確定爲什麼映射沒有發生。 –

+0

這個問題現在已經解決,這是我的錯誤。列表名稱在兩個實體中都不相同,並且在通過幾次SO查詢閱讀後,我瞭解到屬性的名稱應該相同。 –

回答

1

,我認爲你應該在DTO類錯誤的類層次,只要在公共類InnerEntityDTO有

public List<InnerMostEntity> InnerMostList { get; set; } 

,你應該把它寫成

public List<InnerMostEntityDTO> InnerMostList { get; set; }