Reputation: 21
I have 2 models, recipe and ingredients. A recipe can have many ingredients, as well as an ingredient can belong to many recipes. The issue I am having is when I try to add, lets say, 3 (Quantity) eggs, I add the same entity 3 times but when I read the model back out, it's just listed once. I'm guessing that it is actually only saving one since it's a "duplicate." See below for more details.
Models:
public class Recipe
{
public int RecipeID { get; set; }
public string Name { get; set; }
public virtual ICollection<Ingredient> Ingredients { get; set; }
}
public class Ingredient
{
public int IngredientID { get; set; }
public string Name{ get; set; }
public virtual ICollection<Recipe> Recipes { get; set; }
}
So let's say I have a Recipe (Cake) that needs 3 eggs (Ingredients). In my code, I would just add an egg (Ingredient) 3 times, and I would expect this to work. But when I read back the Recipe it only has the egg (Ingredient) once. I'm guessing that it's adding a RecipeID to the Ingredient and then loading that single Ingredient, but how do I get past this? Below is the code I am using to add the Ingredients to my Recipe.
[HttpPost]
public ActionResult Create(Recipe recipe, List<Ingredient> ingredients)
{
// for example, add ingredient egg 3 times
foreach (var item in ingredients)
{
recipe.Ingredients.Add(item);
}
db.Recipes.Add(recipe);
db.SaveChanges();
}
Hopefully I didn't have a typo in the code, but it does all work. It iterates through the foreach
loop as many times as it's suppose to and everything saves fine. Like I said previously, I'm pretty sure it's just updating the Ingredient item with a RecipeID, so it's actually only linking one copy. Thanks in advance!
PS: This is my first post, be gentle! :) And I have searched this extensively before posting here
Edit: Based on comment by Satish Nissankala, I just created another class that handles what I need.
public class RecipeContents
{
public int RecipeContentsID { get; set; }
public int RecipeID { get; set; }
public int Quantity { get; set; }
public Ingredient Ingredient { get; set; }
}
And then I added this to my Recipe
class.
public List<RecipeContents> Ingredients { get; set; }
Upvotes: 1
Views: 166
Reputation: 141
Try adding a string property quantity in Ingredient class. All you need to do then is to update quantity to 3 for eggs. Doing so will only require you to update the property instead of adding the same ingredient thrice. If it is any other ingredient you can just add ounces or table spoon or number of cups all in string. Then retrieving and showing quantity will suffice. Let me know if it is helpful?
Upvotes: 0