1

今天,当我尝试从包含外键字段的 LINQ 查询返回对象数组时,我第一次偶然发现了这个问题。Microsoft 离开 Newtonsoft JSON Library for .NET Core 3+ 的举动让我不知道如何执行下面显示的等效方法:

下面的示例曾经在 Core 2.2 中工作,但现在抛出错误“System.Text.Json.JsonException:检测到不支持的可能对象循环。这可能是由于循环或对象深度大于最大允许深度 32 造成的。

    public async Task<IActionResult> OnGetSelectAllReportTemplatesAsync()
    {
        // Get the currently logged in user.
        var currentlyLoggedInUser = await _userManager.GetUserAsync(User);

        // Note - ApplicationUserId is a foreign key field in the DB Table...
        var reportTemplates = _context.ReportTemplate
            .Where(s => s.Private == true & s.ApplicationUserId == currentlyLoggedInUser.Id)
            .OrderBy(s => s.Name).ToListAsync();

        return new JsonResult(reportTemplates);
    }

下面的 Ajax 调用:

$.ajax({
            type: "GET",
            url: "/Reports/ListView?handler=SelectAllReportTemplates",
            contentType: "json",
            dataType: "json",
            success: function (data) {
                data.forEach(function (element) {
                    $("#editReportTemplateSelect").append('<option value="' + element.id + '">' + element.name + '</option>');
                    reportTemplatesArray.push({ id: '' + element.id + '', name: '' + element.name + '', description: '' + element.description + '', timePeriod: '' + element.timePeriod + '', startDate: '' + element.startDate + '', startTimeHours: '' + element.startTimeHours + '', startTimeMinutes: '' + element.startTimeMinutes + '', endDate: '' + element.endDate + '', endTimeHours: '' + element.endTimeHours + '', endTimeMinutes: '' + element.endTimeMinutes + '', logLevel: '' + element.logLevel + '', eventCategory: '' + element.eventCategory + '', eventType: '' + element.eventType + '', eventSource: '' + element.eventSource + '', userAccount: '' + element.userAccount + '', private: '' + element.private + '', });
                });
                $("#reportTemplateNameInput").val(''); // Clear the department name input field.
                $('#reportTemplateDescriptionTextarea').val(''); // Clear the department description textarea.
            },
            error: function () {
                $("#editreportTemplateSelectMessageBar").html("Error while making Ajax call!");
                setTimeout(function () { $("#editreportTemplateSelectMessageBar").html(''); }, 5000);
            }
        });

我尝试使用属性“[JsonIgnore]”标记模型类中的外键字段,因为我实际上不需要从其他表中读取嵌套属性,我只需要 ApplicationUserId 字符串值本身。我使用关系表的唯一原因是级联删除。

我找不到任何解释如何使用较新系统的代码示例?

4

1 回答 1

1

好的,所以在将以前的 JSON 功能(Microsoft.AspNetCore.Mvc.NewtonsoftJson 补丁)作为 NuGet 安装回项目后,我的线路在这里有点交叉,我仍然遇到对象循环错误。

我的解决方案是在模型类中使用属​​性 [JsonIgnore] 设置外键字段,然后我更新了 OnGet 方法,如下所示。该方法现在使用更简化的 LINQ 查询,该查询没有错误地通过,然后我从选择中手动进行过滤,然后创建一个列表,然后可以将其返回给 Ajax GET 函数。

型号类:

public class ReportTemplate
{
    public int Id { get; set; } // Primary Key

    other parameter object here...

    [Required]
    [JsonIgnore]
    public string ApplicationUserId { get; set; }

    [JsonIgnore]
    public ApplicationUser ApplicationUser { get; set; }
}

剃刀页面模型:

public async Task<IActionResult> OnGetSelectAllReportTemplates()
    {
        // Get the currently logged in user.
        var currentlyLoggedInUser = await _userManager.GetUserAsync(User);

        // Create a List
        List<ReportTemplate> reportTemplates = new List<ReportTemplate>();

        // Run a simple get all LINQ query
        var reports = _context.ReportTemplate.OrderBy(s => s.Name);

        // Do the filtering, manually from the query collection 
        foreach (var report in reports)
        {
            if (report.Private == false)
            {
                reportTemplates.Add(report);
            }
            if (report.Private == true & report.ApplicationUserId == currentlyLoggedInUser.Id)
            {
                reportTemplates.Add(report);
            }
        }

        return new JsonResult(reportTemplates);
    }
于 2019-12-31T15:40:33.153 回答