How to implement one to many relationship
I'm trying to build a recipe app for my spouse. I'm trying to set it up so she can add new recipes to the database as the app grows. When adding new recipe, she will have three drop-down to pick from to construct her new recipe ingredients. First one will contain a list of ingredients that she can choose from, the second one a list of measuring units and the third one a list of quantities. Here is what I got so far. Am I heading in the right direction or am I off? I'm using Entity Framework with a code-first approach: I have created these tables I just don't know how to connect them to a recipe table and how can I add more then one ingredient to a single recipe public class Ingredients
public class IngredientController : Controller
{
private readonly FoodStoreContext _db;
public IngredientController(FoodStoreContext db)
{
_db = db;
}
public IActionResult Index()
{
IEnumerable<Ingredients> ingredientList = _db.ingredients.Include(u => u.MeasureUnit).Include(u => u.QuantityUnit);
return View(ingredientList);
}
[HttpGet]
public IActionResult Upsert(int? id)
{
Ingredients ingredients = new Ingredients();
IEnumerable<SelectListItem> measureUnitList = _db.measureUnit.Select(u => new SelectListItem{ Text = u.Name, Value = u.Id.ToString() });
IEnumerable<SelectListItem> quantityUnitList = _db.quantityUnit.Select(u => new SelectListItem{ Text = u.Name, Value = u.Id.ToString() });
if (id != 0)
{
ViewBag.measureUnitList = measureUnitList;
ViewBag .quantityUnitList = quantityUnitList;
return View(ingredients);
}
else
{
}
return View(ingredients);
}
[HttpPost]
public IActionResult Upsert(Ingredients obj)
{
if (ModelState.IsValid)
{
_db.ingredients.Add(obj);
_db.SaveChanges();
}
return RedirectToAction("Index");
}
}
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; }
}
public class Ingredients
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
[Required]
public int MeasureUnitId { get; set; }
[ValidateNever]
public MeasureUnit MeasureUnit { get; set; }
[Required]
public int QuantityUnitId { get; set; }
[ValidateNever]
public QuantityUnit QuantityUnit { get; set; }
}