问题描述
我正在使用 Entity Framework,但在将父子数据传输到浏览器时遇到问题.这是我的课程:
I am using Entity Framework and having a problem with getting parent and child data to the browser. Here are my classes:
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; }
}
我正在使用以下代码返回问答数据:
I am using the following code to return the question and answer data:
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 将数据获取到浏览器时,我收到以下消息:
On the C# side this seems to work however I notice that the answer objects have references back to the question. When I use the WebAPI to get the data to the browser I get the following message:
ObjectContent`1"类型未能序列化内容类型application/json;"的响应正文;charset=utf-8'.
The 'ObjectContent`1' type failed to serialize the response body for content type 'application/json; charset=utf-8'.
检测到类型为Models.Core.Question"的属性question"的自引用循环.
Self referencing loop detected for property 'question' with type 'Models.Core.Question'.
这是因为问题有答案,而答案有对问题的引用吗?我看过的所有地方都建议在孩子身上提到父母,所以我不知道该怎么做.有人可以给我一些建议吗?
Is this because the Question has Answers and the Answers have a reference back to Question? All the places I have looked suggest having a reference to the parent in the child so I am not sure what to do. Can someone give me some advice on this.
推荐答案
这是因为问题有答案,而答案有参考回问题?
Is this because the Question has Answers and the Answers have a reference back to Question?
是的.无法序列化.
请参阅 Tallmaris 的答案和 OttO 的评论,因为它更简单并且可以全局设置.
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
旧答案:
将 EF 对象 Question
投影到您自己的中间对象或 DataTransferObject.然后这个Dto就可以序列化成功了.
Project the EF object Question
to your own intermediate or DataTransferObject. This Dto can then be serialized successfully.
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;
}
这篇关于检测到自引用循环 - 从 WebApi 取回数据到浏览器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!