1
What happens
I’m having a problem using Entity with my application MVC
. What happens is that when converting a class to JSON the program enters an infinite loop and ends up returning no-content
Example
Taking the relationship as an example (1-n):
A Autor
has several Posts
.
What I realized by debugging is that with a 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 that’s not really my class situation, but what happens is the same idea. When I go to see in my API the answer is no-content
. When I insert [JsonIgnore]
in my properties that is adjusted, but then I lose one side of the relationship, which is a price I cannot pay for the operation of the application.
I would like to know how to proceed and do the Entity
do not 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;
}
Post the code you’re using for such a buddy routine
– Victor Laio
Add your code so we can help you.
– Pedro Paulo
Edited question, with code added. There I explain that, the way it is, it works, but to do a search of users of a Team for example, I can no longer.
– Nicolas S.
How you are converting your object to JSON?
– Pedro Paulo