我想创建一个食谱网站,在那里你可以添加/修改/删除食谱,每个模型都应该有一个配料的列表,与所需的量的那个配料。
我试图使用这样的dict:public idictionary
,但结果是EF Core并不真正喜欢dicts的思想,所以我试图创建一个“映射器”模型,如下所示:
public class RecipeIngredient
{
public int Id { get; set; }
public int IngredientId { get; set; }
public Ingredient Ingredient { get; set; }
public int Quantity { get; set; }
}
问题是,它仍然没有真正起作用。我不能添加菜谱,也不能删除,因为它进入了一个永远循环。
你将如何实施它?
谢谢
试试看:
public class Recipe
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<RecipeIngredient> RecipeIngredients
}
public class Ingridient
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ICollection<RecipeIngredient> RecipeIngredients
}
public class RecipeIngredient
{
public int Id { get; set; }
public int RecipeId { get; set; }
public Recipe Recipe{ get; set; }
public int IngredientId { get; set; }
public Ingredient Ingredient { get; set; }
public int Quantity { get; set; }
}
// and db context:
modelBuilder.Entity<RecipeIngredient>(entity =>
{
entity.HasOne(d => d.Recipe)
.WithMany(p => p.RecipeIngredients)
.HasForeignKey(d => d.RecipeId)
.OnDelete(DeleteBehavior.ClientSetNull);
entity.HasOne(d => d.Ingredient)
.WithMany(p => p.RecipeIngredients)
.HasForeignKey(d => d.IngredientId);
});