.Net Core 3 和 EF Core 3 包含问题 (JsonException)

2024-03-29

我正在尝试使用 .NET Core 3 和 EF Core 开发应用程序。我遇到了一个错误,但找不到解决方案。我无法在“.Net Core 3”上做一个可以用 PHP eloquent 简单创建的结构。

Model;

public NDEntityContext(DbContextOptions<NDEntityContext> options)
            : base(options)
        { }

        public DbSet<User> Users { get; set; }
        public DbSet<Order> Orders { get; set; }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<User>(entity =>
            {
                entity.Property(u => u.CreatedAt)
                    .HasDefaultValueSql("DATEADD(HOUR, +3, GETUTCDATE())");

                entity.HasMany(u => u.Orders)
                    .WithOne(o => o.User);
            });
            modelBuilder.Entity<Order>(entity =>
            {
                entity.Property(o => o.CreatedAt)
                    .HasDefaultValueSql("DATEADD(HOUR, +3, GETUTCDATE())");

                entity.HasOne(o => o.User)
                    .WithMany(u => u.Orders)
                    .HasForeignKey(o => o.UserId)
                    .HasConstraintName("Fk_Order_User");
            });
        }
    }

    public class User : EntityBase
    {
        public int UserId { get; set; }
        public string FirstName { get; set; }
        public string LastName { get; set; }
        public string FullName { get; set; }
        public int Type { get; set; }
        public string Email { get; set; }
        public string Phone { get; set; }
        public string Password { get; set; }
        public string Gender { get; set; }
        [IgnoreDataMember]
        public string HomePhone { get; set; }
        [IgnoreDataMember]
        public string WorkPhone { get; set; }
        public DateTime? BirthDate { get; set; }
        public string SmsConfCode { get; set; }
        public bool IsActive { get; set; }
        public bool IsOutOfService { get; set; }

        public ICollection<Order> Orders { get; set; }
    }

    public class Order : EntityBase
    {
        public int OrderId { get; set; }

        public int UserId { get; set; }
        public User User { get; set; }

        public decimal Price { get; set; }
    }

用户控制器:

[Route("api")]
    [ApiController]
    public class UserController : ControllerBase
    {
        private readonly NDEntityContext _context;
        private readonly ILogger<UserController> _logger;

        public UserController(ILogger<UserController> logger, NDEntityContext context)
        {
            _logger = logger;
            _context = context;
        }

        [HttpGet("users")]
        public async Task<ActionResult<IEnumerable<User>>> GetUsers()
        {
            _logger.LogInformation("API Users Get");
            return await _context.Users.ToListAsync();
        }

        [HttpGet("user/{id:int}")]
        public async Task<ActionResult<User>> GetUser(int id)
        {
            _logger.LogInformation("API User Get");
            return await _context.Users.Include(u => u.Orders).FirstOrDefaultAsync(e => e.UserId == id);
        }
    }

Startup ConfigureServices;

services.AddControllersWithViews().AddNewtonsoftJson(opt => opt.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore);

services.AddDbContext<NDEntityContext>(options =>
    options.UseSqlServer(Configuration.GetConnectionString("DevConnection")));

services.AddSwaggerGen(c =>
{
    c.SwaggerDoc("v1", new OpenApiInfo { Title = "ND API", Version = "v1" });
});

localhost/api/users/;

[
  {
    "userId": 1,
    "firstName": "John",
    "lastName": "Doe",
    "fullName": "John Doe",
    "type": 1,
    "email": "[email protected] /cdn-cgi/l/email-protection",
    "phone": "01234567890",
    "password": "123456789",
    "gender": "Man",
    "homePhone": "123456789",
    "workPhone": "987654321",
    "birthDate": null,
    "smsConfCode": null,
    "isActive": true,
    "isOutOfService": false,
    "orders": null,
    "createdAt": "2019-10-01T21:47:54.2966667",
    "updatedAt": null,
    "deletedAt": null
  }
]

localhost/api/user/1/;

System.Text.Json.JsonException: A possible object cycle was detected which is not supported. This can either be due to a cycle or if the object depth is larger than the maximum allowed depth of 32.
   at System.Text.Json.ThrowHelper.ThrowInvalidOperationException_SerializerCycleDetected(Int32 maxDepth)
   at System.Text.Json.JsonSerializer.Write(Utf8JsonWriter writer, Int32 originalWriterDepth, Int32 flushThreshold, JsonSerializerOptions options, WriteStack& state)
   at System.Text.Json.JsonSerializer.WriteAsyncCore(Stream utf8Json, Object value, Type inputType, JsonSerializerOptions options, CancellationToken cancellationToken)
   at Microsoft.AspNetCore.Mvc.Formatters.SystemTextJsonOutputFormatter.WriteResponseBodyAsync(OutputFormatterWriteContext context, Encoding selectedEncoding)
   at Microsoft.AspNetCore.Mvc.Formatters.SystemTextJsonOutputFormatter.WriteResponseBodyAsync(OutputFormatterWriteContext context, Encoding selectedEncoding)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResultFilterAsync>g__Awaited|29_0[TFilter,TFilterAsync](ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResultExecutedContextSealed context)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.ResultNext[TFilter,TFilterAsync](State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.InvokeResultFilters()
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeNextResourceFilter>g__Awaited|24_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Rethrow(ResourceExecutedContextSealed context)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeFilterPipelineAsync>g__Awaited|19_0(ResourceInvoker invoker, Task lastTask, State next, Scope scope, Object state, Boolean isCompleted)
   at Microsoft.AspNetCore.Mvc.Infrastructure.ResourceInvoker.<InvokeAsync>g__Awaited|17_0(ResourceInvoker invoker, Task task, IDisposable scope)
   at Microsoft.AspNetCore.Routing.EndpointMiddleware.<Invoke>g__AwaitRequestTask|6_0(Endpoint endpoint, Task requestTask, ILogger logger)
   at Microsoft.AspNetCore.Authorization.AuthorizationMiddleware.Invoke(HttpContext context)
   at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)

HEADERS
=======
Accept: application/json
Accept-Encoding: gzip, deflate, br
Accept-Language: tr,en;q=0.9
Connection: close
Cookie: .AspNet.Consent=yes
Host: localhost:44352
Referer: https://localhost:44352/swagger/index.html
User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/77.0.3865.90 Safari/537.36
sec-fetch-mode: cors
sec-fetch-site: same-origin

当我删除时.Include(u => u.Orders)代码我可以像在localhost/api/users/。当我使用 Include 时,我看到此错误

我希望得到这样的答复;

{
  "userId": 0,
  "firstName": "string",
  "lastName": "string",
  "fullName": "string",
  "type": 0,
  "email": "string",
  "phone": "string",
  "password": "string",
  "gender": "string",
  "birthDate": "2019-10-02T18:24:44.272Z",
  "smsConfCode": "string",
  "isActive": true,
  "isOutOfService": true,
  "orders": [
    {
      "orderId": 0,
      "userId": 0,
      "price": 0,
      "createdAt": "2019-10-02T18:24:44.272Z",
      "updatedAt": "2019-10-02T18:24:44.272Z",
      "deletedAt": "2019-10-02T18:24:44.272Z"
    }
  ],
  "createdAt": "2019-10-02T18:24:44.272Z",
  "updatedAt": "2019-10-02T18:24:44.272Z",
  "deletedAt": "2019-10-02T18:24:44.272Z"
}

对于 .NET Core 3,NewtonJson 刚刚发布了一个新补丁。当我安装包时问题就解决了Microsoft.AspNetCore.Mvc.NewtonsoftJson.

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

.Net Core 3 和 EF Core 3 包含问题 (JsonException) 的相关文章

随机推荐

  • 创建测验表单 symfony

    我正在尝试在 symfony 中进行测验 但我在渲染方面遇到了困难 这是我的数据库 一个序列 测验 可以有许多问题 这些问题有多个答案 用户可以选择一个答案 但它的构建方式 我不知道如何创建一个简单的表单 因此当用户选择答案时 它会更新该用
  • 使用 fread、data.table 包读取链 (+, -) 列

    我正在尝试使用 fread 将基因组比对读入data table在 R 中 这是对齐文件的快照 USI EAS28 1 100 1786 674 0 1 1 maternal 68326824 CTCAATTATACTGAAAGAAACAC
  • 如何使用 Python/Tkinter 制作菜单栏剪切/复制/粘贴

    我想制作可以剪切 复制 粘贴所选文本的菜单项 在菜单栏中 而不是在右键单击弹出窗口中 等效的键盘命令已经可以工作 而无需我做任何事情来启用它们 例如 我可以在输入框中输入文本 使用 Control X 剪切它 然后使用 Control C
  • 方法executeScript(selenium web driver)无法定义全局变量以供以后使用?

    我正在使用该方法executeScript在 selenium web 驱动程序中 我发现一个问题 js executeScript var b 1 js executeScript alert b 运行上面的代码后 我想得到一个警报窗口
  • 从 JSON 中的不同嵌套级别提取对象名称

    我一直在尝试从之前的问题中找到解决方案来运行here https stackoverflow com questions 18830955 get the elements from nested json with python usin
  • Android Gradle 构建中出现意外的节点 Android 打包

    我正在尝试让我的项目使用gradle 问题是 每次我尝试构建时 都会收到以下错误 Error Internal error java lang AssertionError Unexpected node Android Packaging
  • 有了websockets,AJAX还有用武之地吗?

    我目前正在使用 Node js 构建一个实时应用程序 我使用 socket io 来支持实时交互 但已加载 jQuery 因此我可以使用 AJAX 我最初使用 socket io 进行服务器和客户端之间的所有通信 我开始认为 AJAX 可能
  • 如何更改 Azure AD 上的用户主体名称

    我正在尝试使用在 Microsoft 文档中找到的 PowerShell 命令 Set MsolUserPrincipalName 更改 Azure AD 用户的用户主体名称here https learn microsoft com en
  • 如何编写将行号输出为列的查询?

    如何编写将行号输出为列的查询 这是 iSeries 上的 DB2 SQL 例如 如果我有 表披头士乐队 John Paul George Ringo 我想写一个声明 如果可能的话 不写过程或视图 这给了我 1 John 2 Paul 3 G
  • 如何从代码隐藏在新窗口或选项卡中打开页面

    所以我有一个 Web 应用程序 我可以从下拉列表中选择一个值 当选择此值时 我想在新窗口中加载另一个页面 我试过这个 ScriptManager RegisterStartupScript Page typeof Page OpenWind
  • 当我访问数组的元素时,硬件级别会发生什么?

    int arr 69 1 12 10 20 113 当我这样做时会发生什么 int x a 3 我一直有这样的印象a 3 意思是这样的 从内存地址开始arr 向前走 3 个内存地址 获取该内存地址表示的整数 但后来我对哈希表的工作原理感到困
  • 从视图模型将焦点设置在 WPF 中的 TextBox 上

    我有一个TextBox and a Button在我看来 现在 我正在检查按钮单击时的条件 如果条件结果为假 则向用户显示消息 然后我必须将光标设置到TextBox控制 if companyref null var cs new Lippe
  • 如何使用 Spring Boot 加载外部配置?

    我目前正在学习如何使用 Spring Boot 到目前为止我从未使用过像Spring这样的框架 而是直接使用文件 FileInputStream等 情况如下 我有一些动态配置值 例如 OAuth 令牌 我想在我的应用程序中使用它们 但我不知
  • Android 中如何使用 MVP 模式控制 ListView

    我目前正在使用 MVP 模式开发 Android 应用程序 当我尝试开发 Activity 时 我应该使用 ListView 所以我对 ListView 使用适配器 但我听说 Adapter 与 MVP 模式上的 Presenter 类似
  • 我们可以用jquery调用智能手机原生的分享功能吗?

    我们可以使用手机 android Iphone 本机共享功能来共享应用程序中的不同内容 是否也可以在所有智能手机中使用 JavaScript 通过浏览器调用此共享功能 这样 在浏览器中的某些事件中 我们可以加载共享小部件 Thanks 是的
  • 使用 shell 删除最旧的文件

    我有一个文件夹 var backup 其中 cronjob 保存数据库 文件系统的备份 它包含一个latest gz zip和许多旧的转储 它们的名称是timestamp gz zip 该文件夹变得越来越大 我想创建一个执行以下操作的 ba
  • Imagecreatefromjpeg 调整大小后返回黑色图像

    我有一个脚本来调整上传图像的大小 但是当我使用它时 它只返回一个黑色方块 所有的错误信息都指向这个函数 function resizeImage image width height scale newImageWidth ceil wid
  • 在 C++ 中检索 std::map 的随机关键元素

    如何在 C 中获取 std map 的随机密钥 使用迭代器 我不想维护额外的数据结构 std map迭代器是双向的 这意味着选择一个随机密钥将是O n 在不使用其他数据结构的情况下 基本上你唯一的选择就是使用std advance随机增量b
  • 无法在 OS X 上安装 netCDF4 python 包

    我正在尝试在 OS X 上安装 netCDF4pip install netCDF4我收到以下错误 usr local bin pip run on Wed Aug 7 23 02 37 2013 Downloading unpacking
  • .Net Core 3 和 EF Core 3 包含问题 (JsonException)

    我正在尝试使用 NET Core 3 和 EF Core 开发应用程序 我遇到了一个错误 但找不到解决方案 我无法在 Net Core 3 上做一个可以用 PHP eloquent 简单创建的结构 Model public NDEntity