I have encountered really weird situation. I am developing a net 5 api, and (among ohther entities) have three tables, Doctor, Specialization, and DoctorSpecialization. My entities:
public class Doctor
{
public int Id { get; set; }
public string Name { get; set; }
public string Resume { get; set; }
public ICollection<DoctorSpecialization1> DoctorSpecializations { get; set; }
}
public class DoctorSpecialization
{
public int Id { get; set; }
public int Doctor1Id { get; set; }
[ForeignKey("Doctor1Id")]
public Doctor1 Doctor { get; set; }
public int Specialization1Id { get; set; }
[ForeignKey("Specialization1Id")]
public Specialization1 Specialization { get; set; }
}
public class Specialization
{
public int Id { get; set; }
public string SpecializationName { get; set; }
}
I want to fetch all the specializations associated with the certain doctor, therefore I created a service:
public class DoctorService : IDoctorService
{
public async Task<List<Specialization>> GetAllSpecializationsForDoctor(int id)
{
var doctor = await _context.Doctors.Where(x => x.Id == id).FirstOrDefaultAsync();
var doctorSpecializations = await _context.DoctorSpecializations.
Where(x => x.DoctorId == doctor.Id)
.ToListAsync();
IEnumerable<int> ids = doctorSpecializations.Select(x => x.SpecializationId);
var specializations = await _context.Specializations.Where(x =>
ids.Contains(x.Id)).ToListAsync();
return specializations;
}
}
In the end, I am adding a method in my controller which is supposed to fetch specializations based on doctor's id:
[HttpGet("specializations/{id}")]
public async Task<ActionResult<List<Specialization1>>> GetSpecializationsForDoctor(int id)
{
var doctor = await _doctorService.FindDoctorById(id);
if (doctor == null) return NotFound();
var specialization = _doctorService.GetAllSpecializationsForDoctor(id);
return Ok(specialization);
}
When I run this in postman, I get the error stated in the title of this question. However, I encountered an article that explains I should install newtonsoft.json and make some changes in my Startup in order to overcome this issue. So therefore I installed Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="5.0.10" and made changes in my Starup as follows:
services.AddControllers().AddNewtonsoftJson(options =>
options.SerializerSettings.ReferenceLoopHandling =
Newtonsoft.Json.ReferenceLoopHandling.Ignore);
This time I get the expected result, but my postman shows tons of data before giving me the wanted result, and I wonder is it ok to return this much data to the client. Can somebody explain me what is going on, tnx in advance!