简体   繁体   中英

Automapper with Entity Framework Core recursive issue

I have a many-to-many relationship with EF Core 2.x.

I have created 3 classes:

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

In my dbcontext , I set up the relationship. Everything works well.

But when I want to Map my Dto Place to my Place Object in my object place I have a recursivity and overflow exception:

I have:

Place

|-> Users

      |-> User

      |-> Place

        |-> Users

          |-> ...

I tried in my config of mapper to use depth but it's not working.

The only workaround I have found is:

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

But it's an ugly solution and not convenient at all.

So which solution can I use?

Thanks,

I added the automapper config:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM