【问题标题】:Automapper with Entity Framework Core recursive issue具有 Entity Framework Core 递归问题的 Automapper
【发布时间】:2020-03-07 01:56:33
【问题描述】:

我与 EF Core 2.x 有多对多关系。

我创建了 3 个类:

public class Place
{
   public string Name {get; set;}
   public int Id {get; set;}
   public ICollection<PlaceUser> Users {get; set;}
}

public class User
{
   public string Name {get; set;}
   public int Id {get; set;}
   public ICollection<PlaceUser> Places {get; set;}
}

public class PlaceUser
{
   public int UserId{get; set;}
   public User User{get; set;}
   public int PlaceId{get; set;}
   public Place Place{get; set;}
}

public class PlaceDto
{
   public string Name {get; set;}
   public int Id {get; set;}
   public ICollection<PlaceUserDto> Users {get; set;}
}

在我的dbcontext 中,我建立了关系。一切正常。

但是当我想将我的 Dto Place 映射到我的对象位置中的 Place 对象时,我遇到了递归和溢出异常:

我有:

Place

|-> Users

      |-> User

      |-> Place

        |-> Users

          |-> ...

我尝试在我的映射器配置中使用深度,但它不起作用。

我发现的唯一解决方法是:

if(place!=null && place.Users!=null)
{  // I set all the place.Users[i].Place = null; and place.Users[i].User=null;}

但这是一个丑陋的解决方案,一点也不方便。

那么我可以使用哪种解决方案?

谢谢,

我添加了自动映射器配置:

configuration.CreateMap<Place, PlaceDto>().MaxDepth(1); 

【问题讨论】:

  • 请展示您如何使用自动映射器的代码。项目到?这根本不支持递归 - 可悲的是。隐藏在文档中,我知道。
  • 当然你有递归。 Placeuser 位于 placeuser 内部,而 place 位于 placeuser 中。我不是专家,但尝试像在所有示例中一样将 Virtual 放在他们两个面前。虚拟仅在需要时加载数据。
  • edit您的问题将您拥有的源代码包含为minimal reproducible example,其他人可以编译和测试。
  • ProjectTo 的主要用例是 EF6。所以,一般来说,ProjectTo 支持 EF6 所支持的。 EF Core 是一个完全不同的野兽。
  • 我添加了我使用的自动映射器配置

标签: c# entity-framework-core automapper


【解决方案1】:

【讨论】:

  • 我需要一次 PlaceUser 的值。然后对于我不再需要的子级别。在您的提议中,它将在第一级 placeuser 设置 null。
  • @dalton5 改变了我的答案。尝试使用它
  • 没有任何效果。我都试过了。在多对多的 efcore 实体中,我递归地递归和加载所有实体。我不能改变它们..
猜你喜欢
  • 1970-01-01
  • 2021-04-28
  • 1970-01-01
  • 2019-04-13
  • 2018-11-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-24
相关资源
最近更新 更多