gpt4 book ai didi

c# - 检测到自引用循环 - 从 WebApi 获取数据到浏览器

转载 作者:IT王子 更新时间:2023-10-29 03:39:23 26 4
gpt4 key购买 nike

我正在使用 Entity Framework,但在将父数据和子数据传输到浏览器时遇到了问题。这是我的类(class):

 public class Question
{
public int QuestionId { get; set; }
public string Title { get; set; }
public virtual ICollection<Answer> Answers { get; set; }
}

public class Answer
{
public int AnswerId { get; set; }
public string Text { get; set; }
public int QuestionId { get; set; }
public virtual Question Question { get; set; }
}

我正在使用以下代码返回问答数据:

    public IList<Question> GetQuestions(int subTopicId, int questionStatusId)
{
var questions = _questionsRepository.GetAll()
.Where(a => a.SubTopicId == subTopicId &&
(questionStatusId == 99 ||
a.QuestionStatusId == questionStatusId))
.Include(a => a.Answers)
.ToList();
return questions;
}

在 C# 方面,这似乎可行,但我注意到答案对象有对问题的引用。当我使用 WebAPI 将数据发送到浏览器时,我收到以下消息:

The 'ObjectContent`1' type failed to serialize the response body for content type 'application/json; charset=utf-8'.

Self referencing loop detected for property 'question' with type 'Models.Core.Question'.

这是因为问题有答案并且答案有对问题的引用吗?我看过的所有地方都建议引用 child 的 parent ,所以我不确定该怎么做。有人可以给我一些建议吗。

最佳答案

Is this because the Question has Answers and the Answers have a reference back to Question?

是的。无法序列化。

编辑:请参阅 Tallmaris 的回答和 OttO 的评论,因为它更简单并且可以全局设置。

GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.Re‌​ferenceLoopHandling = ReferenceLoopHandling.Ignore;

旧答案:

将 EF 对象 Question 投影到您自己的中间体或 DataTransferObject。然后可以成功序列化此 Dto。

public class QuestionDto
{
public QuestionDto()
{
this.Answers = new List<Answer>();
}
public int QuestionId { get; set; }
...
...
public string Title { get; set; }
public List<Answer> Answers { get; set; }
}

类似于:

public IList<QuestionDto> GetQuestions(int subTopicId, int questionStatusId)
{
var questions = _questionsRepository.GetAll()
.Where(a => a.SubTopicId == subTopicId &&
(questionStatusId == 99 ||
a.QuestionStatusId == questionStatusId))
.Include(a => a.Answers)
.ToList();

var dto = questions.Select(x => new QuestionDto { Title = x.Title ... } );

return dto;
}

关于c# - 检测到自引用循环 - 从 WebApi 获取数据到浏览器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17313632/

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