将多个模型组合成 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;

}


慕桂英3389331
浏览 190回答 2
2回答

噜噜哒

我将从定义 DTO 对象开始,因为直接返回数据库对象不是最佳实践,您通常不希望重新查看所有字段,它还为您在不破坏 API 合同的情况下更改数据库结构提供了更大的灵活性。此外,您需要将您的集合包装在 Sections 属性中,因此您不能只返回对象列表。所以,你需要这样的结构:public class SectionsResponse{&nbsp; &nbsp; public List<SectionDTO> Sections {get;set;}}public class SectionDTO{&nbsp; &nbsp; public string SectionID {get;set;}&nbsp; &nbsp; .... add other properties&nbsp; &nbsp; public List<ContentDTO> sectionContent {get;set;}}public class ContentDTO{&nbsp; &nbsp;... define your properties}下一步将是实现数据库对象和 DTO 之间的映射。为此,您可以使用现有的库,例如AutoMapper至于使用数据库,您可以应用从实体框架急切加载。简而言之,它看起来像: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)) };

明月笑刀无情

如果您使用的是实体框架 (EF) 并且您的表关系类型是一对多,您可以在 lambda 表达式中使用Include来返回带有第二个表数据的第一个表。return context.Entity1st.Include(x => x.Entity2nd);或者你也可以这样做:var entities = context.Entity1st;foreach (var entity in entities){&nbsp; &nbsp; entity.Entity2nd = context.Entity2nd.Where(x => x.Entity1stId == entity.Id);}return entities;
打开App,查看更多内容
随时随地看视频慕课网APP