Home > database >  EF Core nested objects
EF Core nested objects

Time:11-02

I have two entities with a many-to-many relationship, and I have a third entity to represent this relationship, these are classroom user and userclassroom respectively. I want to retrieve a specific classroom, users registered in this classroom, and messages from this classroom, I wrote the following query for this:

await _genericRepository.GetAsync(x => x.Id.ToString() == request.classroomId,
                                  x => x.Messages, x => x.Tags, x => x.Users);

But the related entities in the returned data are constantly repeating themselves, you can check it from the picture below.

enter image description here

Is this normal or is it an error, if it is an error, what is the solution?

Entities:

public class AppUser: IdentityUser
{
   public ICollection<UserClassroom> Classrooms { get; set; }
   public List<Message> Messages { get; set; }
}

public class Classroom
{
    public Guid Id { get; set; }
    public string Name { get; set; }
    public List<Tag> Tags { get; set; }
    public List<Message> Messages { get; set; }
    public virtual ICollection<UserClassroom> Users { get; set; }
}

public class UserClassroom
{
    public string UserId { get; set; }
    public Guid ClassroomId { get; set; }
    public AppUser AppUser { get; set; }
    public Classroom Classroom { get; set; }
    public DateTime JoinDate { get; set; } = DateTime.Now;
}

CodePudding user response:

It looks like you have a circular dependency between Classroom and UserClassroom.

Classroom has a collection of UserClassroom, and each UserClassroom has a Classroom which will point back to the Classroom which will point back to the UserClassroom which will... - you get the point.

I would suggest you remove the Classroom property from UserClassroom as you already have the ClassroomId that you can use to retrieve the Classroom if you need to.

CodePudding user response:

This isn't an error. Even for 1:n relations you can have this behaviour. It simply says you have Navigation Properties in both ways.

Let's say you have the classes: Pet, PetOwner. When the navigation properties are set correctly you can access the Pet of an PetOwner. The Pet then holds the PetOwner reference, which again holds the Pet reference. And that way you can navigate indefinitly.

  • Related