vendredi 27 décembre 2019

ThenInclude with many to many in EF Core

I have the following tables:

public class ParentEntity
  {
    public long Id { get; set; }

    [ForeignKey("ParentId")]
    public List<PersonEntity> Persons { get; set; }
  }
public class PersonEntity
  {
    public long Id { get; set; }

    public long ParentId { get; set; }

    [ForeignKey("PersonId")]
    public List<FriendEntity> Friends { get; set; }
  }
public class FriendEntity
  {
    public long PersonId { get; set; }

    public long FriendId { get; set; }

    [ForeignKey("FriendId")]
    public PersonEntity Friend { get; set; }
  }

The Friend table is a many-to-many relationship between two rows of the Person table.

I want to get all parents with all persons and all their friends, which would look like this:

var entities = context.Parents
        .AsNoTracking()
        .Include(c => c.Persons)
        .ThenInclude(i => i.Friends)
        .ToList();

However this does not get the data from the Friends table.

If I inlcude the friends in a person query without the parent it works:

var entities = context.Persons
        .AsNoTracking()
        .Include(i => i.Friends)
        .ToList();

How can I make the first query to retrieve the firends of a person as well and what is causing this behavior?




Aucun commentaire:

Enregistrer un commentaire