我遇到过非常奇怪的情况。我正在开发一个 net 5 api,并且(在其他实体中)有三个表:Doctor、Specialization 和 DoctorSpecialization。我的实体:
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; }
}
我想获取与某个医生相关的所有专业,因此我创建了一项服务:
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;
}
}
最后,我在控制器中添加了一个方法,该方法应该根据医生的 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);
}
当我在邮递员中运行此命令时,我收到此问题标题中所述的错误。但是,我遇到一篇文章,解释我应该安装 newtonsoft.json 并在启动中进行一些更改才能解决此问题。因此,我安装了 Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="5.0.10" 并在我的 Startup 中进行了如下更改:
services.AddControllers().AddNewtonsoftJson(options =>
options.SerializerSettings.ReferenceLoopHandling =
Newtonsoft.Json.ReferenceLoopHandling.Ignore);
这次我得到了预期的结果,但是我的邮递员在给我想要的结果之前显示了大量的数据,我想知道是否可以将这么多数据返回给客户端。有人可以向我解释一下发生了什么事吗,提前tnx!
显然解决方案是如此简单,我错过了等待:
var specialization = await
_doctorService.GetAllSpecializationsForDoctor(id);
我再次设法通过 stackoverflow 找到解决方案,因为显然其他人也遇到了这个问题: JsonException:检测到可能不支持的对象循环。这可能是由于循环或对象深度大于
所以请大家不要像我一样肤浅,一定要使用await,节省大家的时间。再次感谢社区:).
您不应该从控制器返回实体。相反,请使用 DTO。我遇到了同样的问题,它与返回整个实体及其关系有关。