views:

269

answers:

1

LINQ to SQL - When inserting a row (and several other rows with FKs that will point to the PK on this row), is it sufficient to execute [context].[MainTable].InsertOnSubmit(row), or do I need to call it for the other rows as well?

Here's a condensed code sample (C#):

//Forgive the contrived example (off the top of my head) :)

//Main row
Order order = new Order
{
    itemId     = (int)    data["itemNumber"],
    address    = (string) data["address"]
};
db.Orders.InsertOnSubmit(order); //would be nice to only have to submit here.

//Related rows
OrderPerson orderPerson = new OrderPerson
{
    Order = order,
    //other things, etc.
    orderRoleId = RoleIds.Customer
};
//Q: need to do "db.OrderPerson.InsertOnSubmit(orderPerson);" here?

OrderHistoryEntry historyEntry = new OrderHistoryEntry
{
    Order = order,
    //other things, etc.
    historyTypeId = HistoryIds.Ordered
};
//Q: need to do "db.OrderHistoryEntry.InsertOnSubmit(historyEntry);" here?

db.SubmitChanges();

Is it sufficient to do: db.Orders.InsertOnSubmit(order); or do I need to also execute InsertOnSubmit for the related rows (orderPerson and historyEntry)?

It would be nice to only run it once on the main row. The MSDN examples do just that, but they all have the relationships reversed (referencing the other rows from main row).

I appreciate your thoughts.

+3  A: 

How about this instead?

Order order = new Order
{
    itemId     = (int)    data["itemNumber"],
    address    = (string) data["address"]
};

OrderPerson orderPerson = new OrderPerson
{
    orderRoleId = RoleIds.Customer
};
order.OrderPersons.Add(orderPerson);

OrderHistoryEntry historyEntry = new OrderHistoryEntry
{
    historyTypeId = HistoryIds.Ordered
};
order.OrderHistoryEntries.Add(historyEntry);

db.Orders.InsertOnSubmit(order);

db.SubmitChanges();
Matt Sherman
I don't know if you need to 'Add' the children to the parent, or if the OP method will work, but this is clearer. And the same with InsertOnSubmit after the Add. This is nice.
Kirk Broadhurst
Hey, thanks for the help!
Roy Tinker
... that is quite a bit clearer.
Roy Tinker