首页 > 解决方案 > 将多个模型组合成 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;
}

标签: c#entity-frameworkasp.net-web-api2

解决方案


我将从定义 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)) };

推荐阅读