今天,当我尝试从包含外键字段的 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 字符串值本身。我使用关系表的唯一原因是级联删除。
我找不到任何解释如何使用较新系统的代码示例?