I made an API for learning using .NET.
This is a simple API where I have Pizzas and Ingredients. I want to get all the pizzas in the database with their ingredients. Something Like this:
[
{
"id": 2,
"name": "Pizza XYZ",
"price": 4.5,
"isPizzaOfTheWeek": false,
"amount": 15,
"pizzaIngredients": [
{
id: 1,
name: 'Onion',
price: '2.00',
cost: '8.00'
}
]
},
]
My entities are these:
public class Pizza
{
[Key]
public int Id { get; set; }
public string Name { get; set; } = null!;
[Column(TypeName = "decimal(5,2)")]
public decimal Price { get; set; }
public bool IsPizzaOfTheWeek { get; set; }
public int Amount { get; set; }
public List<PizzaIngredient> PizzaIngredients { get; set; } = null!;
}
public class Ingredient
{
[Key]
public int Id { get; set; }
public string Name { get; set; } = null!;
[Column(TypeName = "decimal(5,2)")]
public decimal Price { get; set; } // Price per 100 g
public List<PizzaIngredient> PizzaIngredients { get; set; } = null!;
}
public class PizzaIngredient
{
[Key]
public int PizzaId { get; set; }
public Pizza Pizza { get; set; } = null!;
[Key]
public int IngredientId { get; set; }
public Ingredient Ingredient { get; set; } = null!;
[Column(TypeName = "decimal(5,2)")]
public decimal Cost { get; set; } // Total Cost of this ingredient for this pizza
}
The problem is that I don't know how to do this.
I try using : var pizzas = await _context.Pizza.Include(p => p.PizzaIngredients).ThenInclude(pi => pi.Ingredient).ToListAsync();
This function brings me all the ingredients data but it's also bringing me repetitive data because "ingredients" have property which is also a List of PizzaIngredients.
I hope everything is clear. If more information is needed, I will write it.