Inserting data into multiple tables using Entity Framework
<p>I have two tables in my database that I am filling via Web API:</p>

<pre><code>Orders
________
OrderID
OrderDate
OrderStatusID
</code></pre>

<p>and</p>

<pre><code>OrderItems
___________
OrderID
ItemID
ItemVersionID
ItemNote
ItemSortOrder
</code></pre>

<p>I need to insert <code>Order</code> and all the items for that order in two tables. <code>OrderID</code> is an identity field generated by the database that I will need for inserting data into <code>OrderItems</code> table.</p>

<p>Primary key for the <code>OrderItems</code> table is a composite key <code>(OrderID, ItemID, ItemVersionID)</code>, it is important since the same order can contain multiple items with the same ID but different Version ID.</p>

<p>I was wondering if I will have to add <code>Order</code> and <code>OrderItems</code> data separately or can do so in a single controller function.</p>

<p>Below are my model classes:</p>

<pre><code> [Table("SN_Orders")]
    public class Order
    {
        [Key]
        public int OrderID { get; set; }
        public DateTime OrderDate { get; set; }
        public int OrderStatusID { get; set; }
        public List&lt;OrderItem&gt; Details { get; set; }
    }

    [Table("SN_OrderItems")]
    public class OrderItem
    {
        [Column(Order = 0), Key]
        public int ItemID { get; set; }
        [Column(Order = 1), Key]
        public int ItemVersionID { get; set; }
        [Column(Order = 2), Key]
        public int OrderID { get; set; }
        public string ItemNote { get; set; }
        public int ItemSortOrder { get; set; }
    }
</code></pre>

<p>And below is my attempt to pass in a list of <code>OrderItems</code> with <code>Order</code>  that did not work out:</p>

<pre><code>[HttpPost]
public IHttpActionResult PostItemToOrder(myClass.Order ord1, List&lt;myClass.OrderItem&gt; itemList)
{
    if (!ModelState.IsValid)
    {
        return BadRequest(ModelState);
    }
    using (MyContext ctx = new MyContext())
    {
        ctx.Orders.Add(ord1);
        ctx.SaveChanges();

        foreach (var item in itemList)
        {
             item.OrderID=ord1.OrderId;
             ctx.OrderItems.Add(item);
             ctx.SaveChanges();
        }
    }
}
</code></pre>

<p>Is that something that is possible to accomplish at once? Or will I have to insert order first, return the <code>OrderID</code> to the calling program and then insert Items?</p>