Web api使用实体框架从一对多关系仅返回一个子对象 [英] Web Api returns only one child object from one to many relationship using Entity Framework
问题描述
我有一个控制器方法,该方法必须返回带有子代集合的父对象。在调试中,我可以看到在执行过程中有很多子项,但是当我捕获json时,它只有一个子项。
I've got a controller method that must return parent object with collection of children. In debug I can see plenty of children during execution but when I catch a json it has only one child.
[Route("api/page/{id}")]
public JsonResult GetPage(int id)
{
var item = db.Pages.Include(p => p.PageContainerTemplates)
.SingleOrDefault(p => p.Id == id);
return Json(item);
}
我有很多孩子,而Entity Framework Core却得到了所有,但响应为json看起来像这样:
I've got many children and Entity Framework Core get them all but response json looks like this:
{
"name": "Index",
"bodyClasses": "full-width-container transparent-header",
"title": "Index",
"pageContainerTemplates": [
{
"position": 8,
"pageId": 1
}
]
}
父母对象看起来像这样:
Parent object looks like this:
public class Page : BaseEntity
{
public string Name { get; set; }
public string BodyClasses { get; set; }
public string Title { get; set; }
public virtual List<PageContainerTemplate> PageContainerTemplates { get; set; }
}
孩子看起来像这样:
public class PageContainerTemplate : BaseEntity
{
public int Position { get; set; }
public int PageId { get; set; }
public Page Page { get; set; }
public int ContainerTemplateId { get; set; }
public ContainerTemplate ContainerTemplate { get; set; }
}
我没有任何其他关系或任何其他键,但是什么是奇怪的是,我在JSON中的独生子没有 containerTemplateId属性
I haven't got any additional relationships or any alternative keys but what is strange is than my only child in json haven't got a "containerTemplateId" attribute
推荐答案
尝试一下:
services.AddMvc().AddJsonOptions(options => {
options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
});
已对问题进行了讨论 https://github.com/aspnet/Mvc/issues/4160 和 https://github.com/aspnet/EntityFramework/issues/4646 另请参见循环引用
The issue was discussed https://github.com/aspnet/Mvc/issues/4160 and https://github.com/aspnet/EntityFramework/issues/4646 also see circular reference
这篇关于Web api使用实体框架从一对多关系仅返回一个子对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!