Additional SQL Server features and topics not covered by specific categories
It seems like you are on the right track with your code-first approach. To establish a one-to-many relationship between your Recipe model and Ingredients model, you can add a navigation property to your Recipe model that references a collection of Ingredients.
Here is an example:
public class Recipe
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<Ingredient> Ingredients { get; set; }
}
public class Ingredient
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public int MeasureUnitId { get; set; }
public virtual MeasureUnit MeasureUnit { get; set; }
public int QuantityUnitId { get; set; }
public virtual QuantityUnit QuantityUnit { get; set; }
public int RecipeId { get; set; }
public virtual Recipe Recipe { get; set; }
}
public class MeasureUnit
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
}
public class QuantityUnit
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
}
Here, the Recipe model has a collection of Ingredients as a navigation property, and the Ingredient model has a Recipe object that references its parent Recipe. You can then use the DbSet.Include method to eagerly load the Ingredients when querying for Recipes.
var recipes = context.Recipes.Include(r => r.Ingredients);
When creating a new Recipe, you can add new Ingredients to its Ingredients collection and then save the changes to the database.
var recipe = new Recipe { Name = "Pizza" };
recipe.Ingredients.Add(new Ingredient { Name = "Flour", MeasureUnitId = 1, QuantityUnitId = 1 });
recipe.Ingredients.Add(new Ingredient { Name = "Tomato sauce", MeasureUnitId = 2, QuantityUnitId = 2 });
context.Recipes.Add(recipe);
context.SaveChanges();
I hope this helps!