Communication decided to do with ICollection . I have the following classes. How do we allow to output all Recipient for a certain group? I try to do this, but ThenInclude it does not allow to get Recipient .

 { var group = db.Groups.Include(x => x.GroupRecipients).ThenInclude(y=>y.) .FirstOrDefault(gr => gr.Id == id); } public class Recipient { public int Id { get; set; } public string Name { get; set; } public string Number { get;set; } public ICollection<grouprecipient> GroupRecipients { get; set; } } public class Group { public int Id { get; set; } public string Name { get; set; } public string Description { get; set; } public ICollection<grouprecipient> GroupRecipients { get; set; } } public class GroupRecipient { public int GroupId { get; set; } public Group Group { get; set; } public int RecipientId { get; set; } public Recipient Recipient { get; set; } } public class ApplicationContext : DbContext { public ApplicationContext(DbContextOptions<ApplicationContext> options) : base(options) { } public DbSet<Group> Groups { get; set; } public DbSet<Recipient> Recipients { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<GroupRecipient>() .HasKey(t => new { t.GroupId, t.RecipientId }); modelBuilder.Entity<GroupRecipient>() .HasOne(sc => sc.Group) .WithMany(s => s.GroupRecipients) .HasForeignKey(sc => sc.GroupId); modelBuilder.Entity<GroupRecipient>() .HasOne(sc => sc.Recipient) .WithMany(c => c.GroupRecipients) .HasForeignKey(sc => sc.RecipientId); } } 

Method in controller

 [HttpGet("{id}")] public Group Get(int id) { var group = db.Groups .Include(x => x.GroupRecipients) .ThenInclude(gr => gr.Recipient) .FirstOrDefault(x => x.Id == id); return group; } 
  • Apparently you tried to add via intellisense, but it seems like in 2017 VS there is a bug for this business. Try manually .ThenInclude(y=>y.Recipient) . - null
  • I don't quite understand the title. Correct if necessary. - 0xdb
  • You forgot to specify DbSet for GroupRecipient - Dmitry Polyanin
  • @null yes, I also met this bug more than once and didn’t understand what was the matter, it means not only me)). It was solved simply by spelling the name manually bypassing intellisense. - Dmitry Polyanin
  • With this .ThenInclude (y => y.Recipient) figured out. It really was in intellisense. But for some reason, the api request (api / groups / 1) gives the following json {"id": 1, "name": "NewTestGroup", "description": "Test Description", "groupRecipients": [{"groupId": 1 That is an incomplete answer. Query: [HttpGet ("{id}")] public Group Get (int id) {var group = db.Groups .Include (x => x.GroupRecipients) .ThenInclude (gr => gr.Recipient) .FirstOrDefault (x => x.Id == id); return group; } - Zaur Yakubov

1 answer 1

The point is this:

  services.AddMvc().AddJsonOptions(options => { options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore; });