I am trying to make a simple linq 2 sql many-to-many, insert some data, work.
Here's a Northwind model that represents many for many:
alt text http://www.iaingalloway.com/images/linq-detail.jpg
Now what I'm trying to do is insert a new order, and if the product does not exist, then insert it at the same time within the same transaction. The error I am getting is:
System.Data.Linq.DuplicateKeyException: Cannot add an entity with a key that is already in use.
So this is my (pseduo) code:
using (SqlContext db = new SqlContext()) { // Get existing or create a new instance. Order newOrder = GetOrder(order.Id) ?? new Order(); // Left to right stuff. newOrder.Foo = order.Foo; // Now associate this new order to a product (which might not exist). if (!order.ProductList.IsNullOrEmpty()) { // We have some products... IList<Order_Detail> orderDetailList = new List<Order_Detail>(); foreach(Models.Product product in order.ProductList) { // Associate each product to the a new order_detail. orderDetailList.Add(new Order_Detail { Product = new SqlContext.Product { Foo = product.Foo } }); } // Now associate all the order_details to this order. newOrder.Order_Details.AddRange(orderDetailList); if (newOrder.Id <= 0) db.InsertOnSubmit(newOrder); db.SubmitChanges(); // <-- exception throw here. } }
I assume that I need to save the products first before I try to save the order? I'm so confused: (
source share