What happens
I'm having a problem using Entity with my MVC
application. What happens is that when converting a class to JSON the program goes into an infinite loop and returns no-content
Example
Taking as an example the relationship (1-n):
A Autor
has several Posts
.
What I realized by debugging is that with a Conversion of JSON
the following interpretation will occur:
An author has several posts. A post has an author. An author has several posts. A post has an author ...
Of course this is not my class situation, but what happens is the same idea. When I see in my API the answer is no-content
. When I enter [JsonIgnore]
in my properties this is set, but then I lose one side of the relationship, which is a price that I can not afford to run the application.
I would like to know how to proceed and make Entity
not to enter this infinite loop.
EDITION: Code
Models
Team.cs
public class Team : TEntity
{
public int ID {get; set;}
public string Function {get; set;}
public int LeaderID {get; set;}
public User Leader {get; set;}
public List<TeamUser> Users {get; set;}
}
TeamUser.cs
public class TeamUser : TEntity
{
public int ID {get; set;}
public int TeamID { get; set; }
public int UserID { get; set; }
//Aqui, sem essa anotação já retornaria "no-content" (acredito eu, devido ao bug do loop)
[JsonIgnore]
public virtual Team Team { get; set; }
public virtual User User { get; set; }
}
User.cs
public class User : TEntity
{
public int ID {get; set;}
...
// o mesmo aqui
[JsonIgnore]
public virtual IList<TeamUser> Teams {get; set;}
// e aqui
[JsonIgnore]
public virtual IList<Team> TeamsLeadered {get; set;}
Entity Configuration Files
TeamConfiguration.cs
...
builder
.Property(t => t.LeaderID)
.HasColumnName("ID_LIDER");
builder
.HasOne(t => t.Leader)
.WithMany(u => u.LeaderedTeams)
.HasForeignKey(t => t.LeaderID);
TeamUserConfiguration.cs
builder
.Property(tu => tu.TeamID)
.HasColumnName("ID_EQUIPE");
builder
.Property(tu => tu.UserID)
.HasColumnName("ID_USUARIO");
builder
.HasOne(tu => tu.Team)
.WithMany(t => t.Users)
.HasForeignKey(tu => tu.TeamID);
builder
.HasOne(tu => tu.User)
.WithMany(u => u.Teams)
.HasForeignKey(tu => tu.UserID);
GetAll ()
public IEnumerable<Team> GetAll()
{
var teams = _context.Teams
.Include(t => t.Leader)
.Include(t => t.Users)
//Aqui eu precisaria de um ThenInclude(t => t.User) mas retorna no-content
.ToList();
return teams;
}