views:

134

answers:

0

I have two entities in Linq to Sql setup as a Parent/Child relationship (Parent can have many Children). I have an existing parent record and trying to create new child records to be "added" to the parent. Let's use the familiar Order and OrderDetails model for explanation.

I am trying a bunch of things to add my "child" to the parent record, but when I call SubmitChanges() on the data context, my newly created data is not "inserted" to the database.

For example, I have 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 wierd thing is that both of these ways of handling things appear to be working on other places of 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 attempting to do? Do I need to explicitly call InsertOnSubmit() for each new item I am creating? Is there now way to tell the model that anything added to the child collection should be added on submit?

Thanks!!