问题描述
我有两个一对多的实体
public class Restaurant {
public int RestaurantId {get;set;}
public string Name {get;set;}
public List<Reservation> Reservations {get;set;}
...
}
public class Reservation{
public int ReservationId {get;set;}
public int RestaurantId {get;set;}
public Restaurant Restaurant {get;set;}
}
如果我尝试使用我的 api 预订餐厅
If I try to get restaurants with reservations using my api
var restaurants = await _dbContext.Restaurants
.AsNoTracking()
.AsQueryable()
.Include(m => m.Reservations).ToListAsync();
.....
我收到错误响应,因为对象包含彼此的引用.有相关帖子推荐创建单独的模型或添加 NewtonsoftJson 配置
I receive error in response, because objects contain references to each other.There are related posts that recommend to create separate modelor add NewtonsoftJson configuration
问题是我不想创建单独的模型,第二个建议没有帮助.有没有办法在没有循环关系的情况下加载数据?*
Problem is that I do not want to create separate model and 2nd suggestion didn't help.Is there any way to load data without cycled relationship ?*
System.Text.Json.JsonException:检测到可能的对象循环不支持.这可能是由于周期或如果对象深度大于最大允许深度 32.System.Text.Json.ThrowHelper.ThrowInvalidOperationException_SerializerCycleDetected(Int32maxDepth) 在 System.Text.Json.JsonSerializer.Write(Utf8JsonWriterwriter, Int32 originalWriterDepth, Int32 flushThreshold,JsonSerializerOptions 选项,WriteStack&状态)在System.Text.Json.JsonSerializer.WriteAsyncCore(Stream utf8Json, Object值,输入类型,JsonSerializerOptions 选项,CancellationToken 取消令牌)在Microsoft.AspNetCore.Mvc.Formatters.SystemTextJsonOutputFormatter.WriteResponseBodyAsync(OutputFormatterWriteContext上下文,Encoding selectedEncoding) 在Microsoft.AspNetCore.Mvc.Formatters.SystemTextJsonOutputFormatter.WriteResponseBodyAsync(OutputFormatterWriteContext上下文,Encoding selectedEncoding) 在Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.g__Awaited|29_0[TFilter,TFilterAsync](ResourceInvoker调用者、任务上一个任务、下一个状态、作用域范围、对象状态、布尔值已完成)在Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResultExecutedContextSealed上下文)在Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.ResultNext[TFilter,TFilterAsync](State&接下来,范围&范围、对象&状态,布尔&已完成)在Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeResultFilters()
*
推荐答案
我在一个新项目中尝试了你的代码,安装包后第二种方法似乎运行良好 Microsoft.AspNetCore.Mvc.NewtonsoftJson 首先用于 3.0
I have tried your code in a new project and the second way seems to work well after installing the package Microsoft.AspNetCore.Mvc.NewtonsoftJson firstly for 3.0
services.AddControllersWithViews()
.AddNewtonsoftJson(options =>
options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore
);
尝试新项目并比较差异.
Try with a new project and compare the differences.
这篇关于检测到不支持的 .Net Core 3.0 可能的对象循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!