Nate23VT
Nate23VT

Reputation: 423

Combine multiple Models into 1 JSON WebAPI response

I am working a bit backwards here and trying to create a web api from a provided JSON example that is being used for the front end. Here is the JSON format.

 {"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"
     }]
}]}

I have created 2 tables (Section & Section Content linked by SectionContentID) and added the tables as models using entity framework. I have then created a controller to return the section table but now is where I am stuck on how to join the section content data into 1 JSON response.

My controller just looks like this:

public IQueryable<Sections> GetSections()
{
    //how do I add db.SectionsContent to Sections linked by the sectionContentID field?
    return db.Sections;
}

Upvotes: 0

Views: 1800

Answers (2)

Sajad Afaghiy
Sajad Afaghiy

Reputation: 596

If you are using entity framework (EF) and your tables relationship type is one to many, you can use Include in lambda expression to return first table with data of second table.

return context.Entity1st.Include(x => x.Entity2nd);

or you can also do as bellow:

var entities = context.Entity1st;

foreach (var entity in entities)
{
    entity.Entity2nd = context.Entity2nd.Where(x => x.Entity1stId == entity.Id);
}

return entities;

Upvotes: 1

Alex Riabov
Alex Riabov

Reputation: 9205

I would start from defining DTO object, since returning database objects directly isn't the best practice, you usually don't want to revial all fields also it gives you more flexibility with changing DB structure without breaking API contract. Also you need your collection to be wrapped in Sections property, so you can't just return a list of objects. So, you need structure like:

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
}

Next step will be to implement mapping between your database object and DTO. You may use existing library for this purpose, e.g. AutoMapper

As for working with database you can apply eagerly loading from Entity Framework. In short it will look like:

return db.Sections.Include(x => x.Content);

or wrapped with DTO and AutoMapper:

return new SectionsResponse() { Sections = mapper.Map<List<Section>, List<SectionDTO>>(db.Sections.Include(x => x.Content)) };

Upvotes: 1

Related Questions