2017-04-21 51 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())); 

现在这个工作,但很明显,现在我要地图三类,而不是两个。有关如何改进此解决方案的任何建议?

相关问题