2017-04-21 57 views
0

需要一些幫助。 我有幾個類,我試圖使用Automapper映射。我正在使用EF內核。 基本域是這樣的:具有相互導航屬性的自動映射器

Public class A 
{ 
    public string Id {get; set;} 
    public string Name {get; set;} 
    public virtual Icollection<AB> AB {get; set;} 
} 

Public class B 
{ 
    public string Id {get; set;} 
    public string Name {get; set;} 
    public virtual ICollection<AB> AB {get; set;} 
} 

Public class AB 
{ 
    public string A_Id {get; set;} 
    public string B_Id {get; set;} 
    public virtual A A {get; set;} 
} 

我的DTO是這樣的:

Public class A_DTO 
{ 
    public string Id {get; set;} 
    public string Name {get; set;} 
    public ICollection<B> Bs {get; set;} 
} 

Public class B_DTO 
{ 
    public string Id {get; set;} 
    public string Name {get; set;} 
    public ICollection<A> As {get; set;} 
} 

現在我卡住的是:

  1. 如何建立映射,使Automapper自動檢索兒童列表(例如,當前'A'的相關'Bs')
  2. 如何配置我的DTO,以便例如爲'A'檢索'Bs'不會暴露'A的導航屬性以防止無限遞歸。

謝謝!

回答

0

部分答案在這裏。我正在研究和發現https://www.exceptionnotfound.net/entity-framework-and-wcf-loading-related-entities-with-automapper-and-reflection/

因此,當DTO不是主體時,我通過刪除導航屬性來更改我的DTO。

Public class A_DTO 
{ 
    public string Id {get; set;} 
    public string Name {get; set;} 
} 

Public class A_Nav_DTO: A_DTO 
{ 
    public ICollection<B> Bs {get; set;} 
} 

,並在我的映射我沒有

CreateMap<A, A_DTO>(); 
CreateMap<A, A_Nav_DTO>() 
    .ForMember(dto => dto.B, map => 
     map.MapFrom(model => 
      model.AB.Select(ab => ab.B).ToList())); 

現在這個工作,但很明顯,現在我要地圖三類,而不是兩個。有關如何改進此解決方案的任何建議?

相關問題