这里需要一些帮助。 我有几个类正在尝试使用 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;}
}
现在我陷入困境的是:
- 如何设置映射,以便 Automapper 自动检索子列表(例如当前“A”的相关“B”)
- 如何配置我的 DTO,例如,检索到的“A”的“B”不会公开“A”的导航属性,以防止无限递归。
谢谢!
最佳答案
这里是部分答案。我正在研究并偶然发现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()));
现在这可行了,但显然现在我必须映射三个类而不是两个。关于如何改进此解决方案有什么建议吗?
关于entity-framework - 具有相互导航属性的自动映射器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43532895/