EF Code First, Web API, Json Serialization Many to Many

Has some serious problem with many, many relationships.

public class Team { public Team() { Users = new HashSet<User>(); } public int Id { get; set; } public string Name { get; set; } public ICollection<User> Users { get; set; } } public class User { public User() { Teams = new HashSet<Team>(); } public int Id { get; set; } public string Username { get; set; } public string Name { get; set; } public string Email { get; set; } public string Phone { get; set; } public string Cell { get; set; } public ICollection<Team> Teams { get; set; } } 

After a new team like this returns

 var currentUser = _ctx.Users.Where(u => u.Username == HttpContext.Current.User.Identity.Name).SingleOrDefault(); teamToAdd.Users.Add(currentUser); var teamAdded = _ctx.Teams.Add(teamToAdd); Save(); return teamAdded; 

I get the following error in the internal response exception:

 "Self referencing loop detected with type 'MatchMaker.Data.Team'. Path 'Users[0].Teams'." 

There is, obviously, a circular link, but I want the Team to be able to have many Users and a User to have many Teams. Is there a way to overcome this with creating a DTO?

+4
source share

Source: https://habr.com/ru/post/1496162/


All Articles