Home > Enterprise >  How to include sub list into the original list in API response object?
How to include sub list into the original list in API response object?

Time:09-11

I created an API and one of the props is called "steps" which is supposed to be a list of 'step' type, the steps list came out as null not a list of steps as I was hoping for, not sure if it is an issue with the API-controller code! I already included steps in the seeded data, by the way

The one-to-many relationship in my recipes API is as follows:

namespace API.Models
{
    public class Recipe
    {
        public int Id { get; set; }
        [Required]
        public string Title { get; set; }
        [Required]
        public string Author { get; set; }
        public int PrepTime { get; set; }
        public DateTime DateCreate { get; set; } = DateTime.UtcNow;
        public string Diet { get; set; }
        [Required]
        public int Servings { get; set; }
        public int UserId { get; set; }
        [Required]
        public string PhotoURL { get; set; }
        [Required]  
        public List<Step> Steps { get; set; }
        public string Cuisine { get; set; }
        public string DishType { get; set; }
        [Required]
        public string Ingredients { get; set; }
        public List<Rating> Ratings { get; set; }
    }
}

namespace API.Models
{
    public class Step
    {
        public int Id { get; set; }
        public string Details{ get; set; }
        public int RecipeId { get; set; }
    }
}

and in my API controller for the endpoint was created as follows:

[HttpGet]
public ActionResult<List<Recipe>> GetRecipes()
{
    var recipes = context.Recipes.ToList();
    
    return Ok(recipes);
}

In swagger, the API response was:

[
  {
    "id": 1,
    "title": "Creamy Chicken and Dumplings",
    "author": "Unknown",
    "prepTime": 30,
    "dateCreate": "2020-04-20T00:00:00",
    "diet": "Non vegetarian",
    "servings": 2,
    "userId": 0,
    "photoURL": "https://i1.wp.com/thecraveablekitchen.com/wp-content/uploads/2017/12/Creamy-Chicken-and-Dumplings-Square-1.jpg?fit=550,550&ssl=1",
    "steps": null,
    "cuisine": null,
    "dishType": null,
    "ingredients": "Heavy cream, chicken",
    "ratings": null
  }
]

CodePudding user response:

Maybe you need to reference step in recipe with stepId.

CodePudding user response:

Are you using Entity Framework? You need to specify that you want to eager-load the steps:

context.Recipes.Include(r => r.Steps).ToList();
  • Related