title: In Entity Framework with MVC, how to create related entity of related entity at same time as main entity?
body: <p>I am creating a simple recipe web app with MVC 6 and Entity Framework 7. </p>
  
  <p>Using scaffolding and a local database with EF, I am trying to allow the user to create ingredients at the same time they create a recipe. However the relationship doesn't seem to have been set up properly because the ingredients are not being saved. The direct relationship to the main model (recipe), the RecipeIngredient, is being saved, but the second relationship (ingredient) is not.  </p>
  
  <p>Not sure if the models are set up wrong or EF isn't supposed to automagically create the ingredients and I need to do something else to get it wired up.</p>
  
  <p>Recipe model:</p>
  
  <pre><code>public int ID { get; set; }
  public int RecipeIngredientID { get; set; }
  public virtual IList&lt;RecipeIngredient&gt; Ingredients { get; set; }
  </code></pre>
  
  <p>RecipeIngredient model:</p>
  
  <pre><code>public int ID { get; set; }
  public virtual Ingredient Ingredient { get; set; }
  public virtual Recipe Recipe { get; set; }
  </code></pre>
  
  <p>Ingredient model:</p>
  
  <pre><code>public int ID { get; set; }
  </code></pre>
  
  <p>EF automatically added foreign keys to the RecipeIngredient database for IngredientID and RecipeID.</p>
  
  <p>In the scaffolded Create.cshtml file for creating recipes, I have added input fields for the ingredient. The @model is Recipe, and the ingredients are referred to with dots. So, property Amount on RecipeIngredient is set with: </p>
  
  <pre><code>&lt;input asp-for="Ingredients[0].Amount"&gt;
  </code></pre>
  
  <p>The above works and is saved on the RecipeIngredient that is then automatically created, but the below doesn't work for creating the Ingredient.</p>
  
  <pre><code>&lt;input asp-for="Ingredients[0].Ingredient.Name"&gt; 
  </code></pre>
  
  <p>Can EF only go one layer deep in automatically creating related entities? Or is this possible and I just have something set up wrong?</p>
  
  <p>Edit: Just noticed that in the latest EF 7 docs, <a href="http://ef.readthedocs.org/en/latest/modeling/relationships.html#many-to-many" rel="nofollow">many-to-many relationships are not yet supported.</a> I tried to add the two one-to-many mappings in ApplicationDbContext.cs (albeit without the foreign keys specified as having the foreign keys explicitly defined on the RecipeIngredient model was causing SqlException conflict errors), but no luck. </p>