在使用MVC的实体框架中,如何与主实体同时创建相关实体的相关实体?

时间:2015-12-04 22:03:57

标签: c# asp.net-mvc database entity-framework

我正在使用MVC 6和Entity Framework 7创建一个简单的配方Web应用程序。

使用脚手架和EF的本地数据库,我试图让用户在创建配方的同时创建成分。然而,这种关系似乎没有得到适当的设置,因为成分没有被保存。与主模型(配方),RecipeIngredient的直接关系正在保存,但第二个关系(成分)不是。

不确定模型是否设置错误或EF不应该自动创建成分,我需要做其他事情才能将其连接起来。

食谱模型:

public int ID { get; set; }
public int RecipeIngredientID { get; set; }
public virtual IList<RecipeIngredient> Ingredients { get; set; }

RecipeIngredient模型:

public int ID { get; set; }
public virtual Ingredient Ingredient { get; set; }
public virtual Recipe Recipe { get; set; }

成分模型:

public int ID { get; set; }

EF自动将外键添加到RecipeIngredient数据库中,用于IngredientID和RecipeID。

在用于创建配方的脚手架Create.cshtml文件中,我添加了配料的输入字段。 @model是Recipe,成分用点表示。因此,RecipeIngredient上的属性Amount设置为:

<input asp-for="Ingredients[0].Amount">

上述工作并保存在RecipeIngredient上,然后自动创建,但下面的内容并不适用于创建成分。

<input asp-for="Ingredients[0].Ingredient.Name"> 

EF只能在自动创建相关实体的过程中深入一层吗?或者这是可能的,我只是设置错了吗?

编辑:刚刚注意到在最新的EF 7文档中,many-to-many relationships are not yet supported.我试图在ApplicationDbContext.cs中添加两个一对多映射(虽然没有指定外键明确定义了外键)在RecipeIngredient模型上导致SqlException冲突错误),但没有运气。

0 个答案:

没有答案