The owner stores more than 20 values. Before sending to customer checked. But, when data arrives at the client, it displays only the first owner`a and that, with only one pet, although he should have 2. Action:

public JsonResult Get() { List<Owner> owners = new List<Owner>(); using (DatabaseContext dbContext = new DatabaseContext()) { Owner owner1 = new Owner { Name = "Vik", PetsCount = 5 }; Owner owner2 = new Owner { Name = "Viki", PetsCount = 7 }; dbContext.Owners.AddRange(new List<Owner> { owner1, owner2 }); dbContext.SaveChanges(); Pet pet1 = new Pet { Name = "Snow", Owner = owner1 }; Pet pet2 = new Pet { Name = "Chrismas", Owner = owner1 }; Pet pet3 = new Pet { Name = "Mary", Owner = owner2 }; dbContext.Pets.AddRange(new List<Pet> { pet1, pet2, pet3 }); dbContext.SaveChanges(); owners = dbContext.Owners.Include(p => p.Pets).ToList(); } var json = new JsonResult(owners); return json; } 

    1 answer 1

    As I read here , in EF with eager loading, I had a cyclic connection between the models:

     public class Pet { public int Id { get; set; } public string Name { get; set; } public int OwnerId { get; set; } public virtual Owner Owner { get; set; } } public class Owner { public int Id { get; set; } public string Name { get; set; } public int PetsCount { get; set; } public List<Pet> Pets { get; set; } public Owner() { Pets = new List<Pet>(); } } 

    And there it was proposed to make a separate model without connections:

     public class OwnerAndPets { public int Id { get; set; } public string OwnerName { get; set; } public int PetsCount { get; set; } public List<string> PetsNames { get; set; } } 

    Now in the place of the owners in the action oap:

     ... List<OwnerAndPets> oap = dbContext.Owners.Include(p => p.Pets).Select(x => new OwnerAndPets { Id = x.Id, OwnerName = x.Name, PetsNames = x.Pets.Select(y => y.Name).ToList(), PetsCount = x.PetsCount }).ToList(); ...