c# - 检测到可能的对象循环。这可能是由于循环或对象深度大于最大允许深度 32
问题描述
我遇到了非常奇怪的情况。我正在开发一个 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 并在我的 Startup 中进行一些更改以克服这个问题。因此,我安装了 Microsoft.AspNetCore.Mvc.NewtonsoftJson" Version="5.0.10" 并在我的 Starup 中进行了如下更改:
services.AddControllers().AddNewtonsoftJson(options =>
options.SerializerSettings.ReferenceLoopHandling =
Newtonsoft.Json.ReferenceLoopHandling.Ignore);
这次我得到了预期的结果,但是我的邮递员在给我想要的结果之前显示了大量的数据,我想知道是否可以将这么多的数据返回给客户端。有人可以提前解释一下发生了什么,tnx!
解决方案
显然解决方案是如此简单,我错过了等待:
var specialization = await
_doctorService.GetAllSpecializationsForDoctor(id);
由于stackoverflow,我再次设法找到了解决方案,因为显然其他人在:JsonException:检测到不支持的可能对象循环时遇到了这个问题。这可能是由于循环或对象深度大于
所以请大家不要像我一样肤浅,一定要使用await,节省你的时间。再次感谢社区:)。
推荐阅读
- javascript - 在 Razor 视图中使用 DataTables 插件 - 无法设置未定义的属性(设置“_DT_CellIndex”)错误
- sql-server - SQL Server 中 v$session.osuser 的等价物
- openssl - OpenSSL TLSv1.3 服务器发出的第一个会话票证的目的是什么?
- html - 引导程序不起作用
- flutter - 电话身份验证凭据无效
- swift - 如何在另一个 api 后调用中使用 json 响应作为参数?
- jooq - jooq 时间戳算术无法从整数转换为 LocalDateTime
- sql - 创建一个 postgres 视图并将 nullalble 字段转换为非空
- tsql - 将 Excel 公式(使用日期和减法)转换为 T-SQL
- python - 在熊猫数据框中应用特定月份和日期的功能