gpt4 book ai didi

c# - 将 Entity Framework 数据转换为 json 时出现 502 错误。可能的递归。如何预防?

转载 作者:太空宇宙 更新时间:2023-11-03 12:54:11 25 4
gpt4 key购买 nike

[HttpGet("/api/notes/suggested")]
public JsonResult GetSuggestedNotes(string searchText)
{
//TODO: Podpowiedzi przy wpisywaniu tytułu
JsonResult result = null;
try {
List<Note> n = db.Notes.Include(x => x.NoteTags).ToList();

result = Json(n);
}
catch(Exception e)
{
Console.WriteLine(e);
}
return result;
}

public class Note
{
public Note()
{
CreationDate = DateTime.Now;
NoteTags = new HashSet<NoteTag>();
Parts = new HashSet<Part>();
}

public int ID { get; set; }
public virtual ICollection<NoteTag> NoteTags { get; set; }
public virtual ICollection<Part> Parts { get; set; }
public DateTime? CreationDate { get; set; }

[NotMapped]
public string TagsToAdd { get; set; }

[NotMapped]
public string TagsAsSingleString {
get
{
string result = "";
foreach(var nt in NoteTags)
{
result += nt.Tag.Name + " ";
}
return result;
}
}
}

public class NoteTag
{
public int NoteId { get; set; }
public virtual Note Note { get; set; }

public int TagId { get; set; }
public virtual Tag Tag { get; set; }
}

当我尝试使用此 WebAPI Controller 获取数据时,我收到 502 错误网关。没有错误,调试服务器时一切正常。数据从数据库正确获取。

我怀疑它可能类似于“无限循环”,但如何防止呢? (Note 类连接到 NoteTag 对象的集合,这些 NoteTag 对象又连接回 Note,这可能会造成这个循环)。

如果出现问题,为什么没有错误? :/

最佳答案

我不知道它是否仍然相关,但我遇到了同样的问题以及配置 Newtonsoft.Json 对我有用的是什么 SerializerSettings.ReferenceLoopHandling = ewtonsoft.Json.ReferenceLoopHandling.Ignore

如果您使用的是 VS2015 MVC,您可以添加以下代码: services.AddMvc().AddJsonOptions(options => options.SerializerSettings.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore);

Startup 类的 ConfigureServices 方法中。

关于c# - 将 Entity Framework 数据转换为 json 时出现 502 错误。可能的递归。如何预防?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34534780/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com