How can I map correctly a model in a model in EF Core 5?

I have a Recipe object which looks like this(all of the code is a simplified sample):

public class Recipe
{
    public int Id { get; set; }

    [Required]
    [StringLength(4000)]
    public string Description { get; set; }

    [Required]
    public virtual ICollection<RecipeIngredient> Ingredients { get; set; } = new List<RecipeIngredient>();
}

As you can see my Recipe object has a List of RecipeIngredient which looks like this:

public class RecipeIngredient
{
    public int Id { get; set; }

    public int IngredientId { get; set; }
    public Ingredient Ingredient { get; set; }

    public int Quantity { get; set; }
}

I needed this new RecipeIngredient model to be able to track how much of each ingredient is needed in the recipe.

The thing is, I have a controller where I try to return every recipe in a list like this:

// GET: api/Recipes
[HttpGet]
public async Task<ActionResult<IEnumerable<Recipe>>> GetRecipes()
{
    return await _context.Recipes.Include(m => m.Ingredients).ToListAsync();
    //return await _context.Recipes.ToListAsync();
}

As you can see there is a commented part where I don’t include the Ingredients list in the model (but I have to get them too) and it works so clearly this include part is the wrong one.

Do you have any idea? I am not sure how to map this, or if introducing a new model is the proper fix for my problem

Answer

If the result you are expecting should look like (as you mentioned in the comment) –

recipe:{"id": 0, "description:"...", "Ingredients": [RecipeIngredient objects]}

then your query should look like –

await _context.Recipes
        .Include(p => p.Ingredients)
        .ThenInclude(p => p.Ingredient)
        .ToList();

Leave a Reply

Your email address will not be published. Required fields are marked *