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!!

+2
.net linq linq-to-sql


source to share


No one has answered this question yet

Check out similar questions:

1496
Multiple "order by" in LINQ
987
LINQ Query on DataTable
939
Group in LINQ
798
What is the Java equivalent for LINQ?
789
When to use. First and when to use .FirstOrDefault with LINQ?
783
Entity Framework vs LINQ to SQL
684
LINQ Aggregate Algorithm Explained
451
LINQ: When To Use SingleOrDefault And FirstOrDefault () With Filter Criteria
3
linq to sql -error when insert at 2 resolves parent child relation
2
How can I remove records from a child collection in LINQ to SQL?



All Articles
Loading...
X
Show
Funny
Dev
Pics