This is my code:
namespace MyProject.Models.Database
{
public class Recipe
{
public Guid Id { get; set; } = Guid.NewGuid();
public string Name { get; set; }
public string? Description { get; set; }
public string? Picture { get; set; }
public int Worktime { get; set; }
public int? Cooktime { get; set; }
public int Difficulty { get; set; }
public int Portions { get; set; }
public List<Ingredient> Ingredients { get; set; }
}
public class Ingredient
{
public Guid Id { get; set; } = Guid.NewGuid();
public Guid IngredientId { get; set; }
public int Qty { get; set; }
public string QtyUnit { get; set; }
}
}
I want the class "Recipe" to include many elements of type "Ingredient". Ive read stuff about One-to-One and Many-To-Many but i just dont get it...
any Ideas? thx
CodePudding user response:
One recipe can consist of many ingredients, one ingredient can also be in many recipes. This is a many-to-many relationship.
What you need to do is create a new class that contains Id
, RecipeId
, IngredientId
.Name that class something like RecipeIngredient. When you are creating a DbSet<RecipeIngredient>
in your db context, name your table RecipesIngredients
.
What should be the data types of the properties in RecipeIngredient
?
The Id
property will be the primary key, you can decide the data type.
RecipeId
will be a foreign key for the Recipe, so it needs the same data type as the primary key of the Recipe (in your case Guid
).
IngredientId
will be the foreign key for the Ingredient
, so the data type will again be Guid
in your case.
Note that instead of putting Id
in your RecipeIngredient, you can create a composite key instead.
When should you do that? -> here
I suggest you learn about the different relationships and how to apply them using C# and Entity Framework Core -> here
Good luck on your learning journey! When you don't feel you understand a topic, don't worry and don't get discouraged, you just need more experience. Keep up the good work :)