entity-framework - 具有相互导航属性的自动映射器

标签 entity-framework automapper entity-framework-core

这里需要一些帮助。 我有几个类正在尝试使用 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”的相关“B”)
  2. 如何配置我的 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/

相关文章:

c# - Entity Framework 6.1.3 从代码优先模型初始化现有但为空的数据库

entity-framework - automapper 是否可以防止使用 EF 进行延迟加载?

c# - AutoMapper 可以在值类型(枚举)和引用类型之间进行映射吗? (字符串)

.net-core - EF Core Migration Add - 使用意外的 DropForeignKey、DropUniqueConstraint、DropColumn 语句创建迁移

c# - EF core 在 ASP.net core 多层架构中添加迁移

c# - 从 DbContext 检索 DbSet<T> 的通用方法

.net - 以编程方式从 SQL 查询生成 edmx 文件

.net - 如何处理 Entity Framework 中缺少主键的问题?

c# - 更新到 Automapper v5 时出现 .NullSubstitute 错误

c# - EF Core 保存所需属性的空值