【发布时间】:2013-06-23 05:05:31
【问题描述】:
我正在使用实体框架,但在将父子数据传输到浏览器时遇到问题。这是我的课程:
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 将数据获取到浏览器时,我收到以下消息:
“ObjectContent`1”类型无法序列化内容类型“application/json;”的响应正文; charset=utf-8'。
检测到类型为“Models.Core.Question”的属性“问题”的自引用循环。
这是因为问题有答案并且答案有对问题的引用吗?我看过的所有地方都建议在孩子身上引用父母,所以我不知道该怎么做。有人可以给我一些建议吗?
【问题讨论】:
-
为你的 web api 使用 Dto,避免在你的响应中直接返回实体
-
什么是 Dto?我们的整个应用程序使用 EF,我们在客户端使用 AngularJS,除了这种情况,我们没有任何问题。
-
我的意思是你应该为你的 Web Api 定义你的 Dto,Dto 有点类似于 MVC 中的 ViewModel。 Dto 就像您的 EF 模型的包装器,为您的客户端 (angularjs) 提供数据。
-
你可以看看我在 “Self Referencing Loop Detected” exception with JSON.Net 页面上的回答。
标签: c# entity-framework serialization asp.net-web-api json.net