Updating Dataset with Foreign key

Posted on: Wed Aug 27 18:21:20 -0700 2008. Updated on: Wed Aug 27 18:21:20 -0700 2008.
Category: .NET C#

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

Comments:

Add a Comment:

simple_captcha.jpg
(human authentication)


Ads

Categories

About

Random foliage

This website is meant to be a reference for ASP Dot Net developers. The entries are a compilation of things I've figured out how to do and that I deem useful to keep of track for future reference. Assumptions: web development with: C Sharp (vb sucks), visual studio 05/08, .net 3.5, meant for programmers. Written by: James Reategui.