我有2個模型,配方和成分。一份食譜可以有很多成分,以及一種成分可以屬於許多食譜。我遇到的問題是當我嘗試添加時,可以說,3個(數量)雞蛋,我添加了相同的實體3次,但是當我讀取模型時,它只被列出一次。我猜測它實際上只是保存一個,因爲它是「重複的」。請參閱下面的更多細節。ASP.NET MVC5多對多關係多個相同記錄
型號:
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; }
}
所以我們可以說我有一個配方(蛋糕),需要3個雞蛋(成分)。在我的代碼中,我只會添加一個雞蛋(配料)3次,我希望這個工作。但是當我回讀食譜時,它只有一次雞蛋(配料)。我在猜測它是將配方ID添加到配料中,然後裝入單一配料,但我該如何克服這個問題?以下是我用來將配料添加到我的食譜中的代碼。
[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();
}
希望我在代碼中沒有錯字,但它確實有效。它循環遍歷foreach
循環多次,因爲它假設並且一切都很好保存。就像我以前說過的,我很確定它只是用RecipeID更新Ingredient項目,所以它實際上只連接一個副本。提前致謝!
PS:這是我的第一篇文章,要溫柔! :) 我在這裏發佈之前已經廣泛搜索了這個
編輯:根據Satish Nissankala的評論,我剛剛創建了另一個類來處理我需要的東西。
public class RecipeContents
{
public int RecipeContentsID { get; set; }
public int RecipeID { get; set; }
public int Quantity { get; set; }
public Ingredient Ingredient { get; set; }
}
然後我說這個我Recipe
類。
public List<RecipeContents> Ingredients { get; set; }
到目前爲止,我能想出的最佳解決方案是根本沒有虛擬成分,它有一個'公開列表 QuantityIngredients {get;組; }'用於存儲數量和IngredientID,然後根據需要加載配料。我相信應該有一個更優雅的方式來做到這一點。這種方式更像是一種黑客攻擊。 –