Updating Dataset with Foreign key
Category: DotNet
So, let's say we have a Dataset for orders and within this dataset we have two tableadapters, one being the master_orders table and the other the child order_details table. The two table adapters are connected by a foreign key relation.
First thing, when you configure the table adapter query, hit the "advanced" button at the bottom and check all three options. Note that the query must be one that allows for Updating. If not these checkboxes will be greyed out.
Now we can have some sample code. The DSOrders contains both tables that need to be inserted/updated:
public DSOrders SaveOrder(DSOrders order)
{
// declare the master and child table adapters
DSOrdersTableAdapters.ordersTableAdapter ordersTa = new DSOrdersTableAdapters.ordersTableAdapter();
DSOrdersTableAdapters.orders_detailTableAdapter detailsTa = new DSOrdersTableAdapters.orders_detailTableAdapter();
// run update for master
ordersTa.Update(order.orders);
// do a foreach loop and set the parent row
foreach (DSOrders.orders_detailRow row in order.orders_detail.Rows)
{
row.SetParentRow(order.orders[0]);
}
// run update for child details table
detailsTa.Update(order.orders_detail);
return order;
}
By the way, this would be a good example of when to use Transactions. Look for my post on using transactions