c# - 将多个模型组合成 1 个 JSON WebAPI 响应
问题描述
我在这里工作有点倒退,并尝试从提供的用于前端的 JSON 示例创建一个 Web api。这是 JSON 格式。
{"Sections": [{
"sectionID":"1",
"sectionOrder":1,
"sectionName":"Approach",
"sectionText": "",
"sectionContent": [{
"contentID": "1",
"contentTitle": "Definition",
"contentText": "Lorem Ipsum",
"contentImage": ""
},
{
"contentID": "2",
"contentTitle": "Vision",
"contentText": "Lorem Ipsum",
"contentImage": "image2.jpg"
}]
}]}
我创建了 2 个表(SectionContentID 链接的部分和部分内容)并使用实体框架将表添加为模型。然后我创建了一个控制器来返回部分表,但现在我被困在如何将部分内容数据加入 1 个 JSON 响应中。
我的控制器看起来像这样:
public IQueryable<Sections> GetSections()
{
//how do I add db.SectionsContent to Sections linked by the sectionContentID field?
return db.Sections;
}
解决方案
我将从定义 DTO 对象开始,因为直接返回数据库对象不是最佳实践,您通常不想修改所有字段,它也为您在不破坏 API 合同的情况下更改数据库结构提供了更大的灵活性。此外,您需要将您的集合包装在 Sections 属性中,因此您不能只返回对象列表。所以,你需要这样的结构:
public class SectionsResponse
{
public List<SectionDTO> Sections {get;set;}
}
public class SectionDTO
{
public string SectionID {get;set;}
.... add other properties
public List<ContentDTO> sectionContent {get;set;}
}
public class ContentDTO
{
... define your properties
}
下一步将是实现数据库对象和 DTO 之间的映射。您可以为此目的使用现有的库,例如AutoMapper
至于使用数据库,您可以从 Entity Framework应用热切加载。简而言之,它看起来像:
return db.Sections.Include(x => x.Content);
或用 DTO 和 AutoMapper 包装:
return new SectionsResponse() { Sections = mapper.Map<List<Section>, List<SectionDTO>>(db.Sections.Include(x => x.Content)) };
推荐阅读
- liferay - 在 Liferay 7.2 中,如何设置角色以仅编辑某些内容页面?
- javascript - 您将如何使用 Javascript 更改值/添加到对象数组内的嵌套对象数据?
- r - 如何在 R 中处理大量时间序列?
- c# - 使用类型参数保存操作的集合 - 无法转换 IEnumerable
到 IEnumerable - javascript - 任何可以模拟 xbox 控制器输入的 node.js 包?包装 ScpDriverInterface dll 失败:/
- adaptive-cards - 发送窗口高度宽度,工具栏=0 menubar=0 在 webex 自适应卡片的 url 中
- sql - SQL - 查找特定组的最小值并提供有关它的扩展信息
- bit-manipulation - 位移如何反转这个无符号短整数
- jquery - jquery 速记 - 让多个选择器匹配各自的 div
- sql - 此 WHERE 子句未返回任何数据