Linq to Sql Add entries for children
I have two objects in Linq to Sql setup as parent / child relationship (parent can have many children). I have an existing parent record and trying to create new child records to add a parent. Use the familiar Order and OrderDetails model for explanation.
I'm trying to add a bunch of stuff to the parent record, but when I call SubmitChanges () in the data context, my newly created data is not "inserted" into the database.
For example, I've tried:
MyDataContext context = new MyDataContext();
Order existingOrder = context.Orders.SingleOrDefault(o => p.OrderID == orderID);
OrderDetail newDetail = new OrderDetail();
//fill in order details here...
//ESTABLISH THE LINK SUCH THAT NEW RECORD IS CREATED
existingOrder.OrderDetails.Add(newDetail);
context.SubmitChanges();
I've also tried:
MyDataContext context = new MyDataContext();
Order existingOrder = context.Orders.SingleOrDefault(o => p.OrderID == orderID);
OrderDetail newDetail = new OrderDetail();
//fill in order details here...
//ESTABLISH THE LINK SUCH THAT NEW RECORD IS CREATED
newDetail.OrderID = existingOrder.OrderID;
newDetail.Order = existingOrder;
context.SubmitChanges();
And a combination of the two:
MyDataContext context = new MyDataContext();
Order existingOrder = context.Orders.SingleOrDefault(o => p.OrderID == orderID);
OrderDetail newDetail = new OrderDetail();
//fill in order details here...
//ESTABLISH THE LINK SUCH THAT NEW RECORD IS CREATED
newDetail.OrderID = existingOrder.OrderID;
newDetail.Order = existingOrder;
existingOrder.OrderDetails.Add(newDetail);
context.SubmitChanges();
The strangest thing is that both of these ways of handling things seem to work elsewhere in the code base. For example:
MyEntity myEntity = context.MyEntities.SingleOrDefault(e => e.MyEntityID = id);
myEntity.SelectedCategories.Add(
new SelectedCategory { MyEntityID = myEntity.MyEntityID , CategoryID = categoryId }
);
context.SubmitChanges(); //correctly adds the new "many-to-many" record
What is the "correct" way to do what I am trying to do? Do I need to explicitly specify InsertOnSubmit () for every new element I create? Is there now a way to tell the model that whatever is added to the child collection should be added to submit?
Thank!!
No one has answered this question yet
Check out similar questions: