具有实体框架核心递归问题的自动映射器



我与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 Object时,我有一个递归和溢出异常:

我有:

Place
|-> Users
      |-> User
      |-> Place
        |-> Users
          |-> ...

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

我找到的唯一解决方法是:

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); 

https://stackoverflow.com/a/48824922/8101300

https://stackoverflow.com/a/57134333/8101300

CreateMap<Foo, Bar>().PreserveReferences();

最新更新