Perley's answer is almost there. However, the problem you will have with
this is concurrency. Let's say your parent table in the database has one row
in it. You insert a row in your dataset, which is disconnected, and at the
same time another user inserts a row in the actual database. Your dataset
will auto-assign an ID of say 2, but the insert that already took place for
the other user already generated a record with an id of 2.
The way around this is actually quite simple. The stored procedure or sql
statement that you are using to insert records into the table from the data
adapter just needs to ignore the ID column on both parent and child records.
That way, when you do the insert, SQL Server will assign its own correct ID
to the parent record, so all you need to do is a reload of the dataset to be
back in sync.
The problem here though is that you still have no way of knowing what to
assign to the child row's ID. The only solution that I can see here is
either to use a stored procedure (which is able to use @@identity to grab
the identity of the new parent record and assign that to the new child
records within the stored proc).
A far far better solution though to the whole problem is not to use standard
identity columns that increment one by one on each insert. Instead, use
GUIDS. These are globally unique. Using Guids your application needs to
generate the guid in code (there is a framework class for this I think) and
assign it to the parent and child records int he dataset. The guids can then
be sent directly to the database on your inserts without concurrency fears.
Hope that helps (and makes sense).
--
Peter Wright
Author of ADO.NET Novice To Pro, from Apress Inc.
_____________________________
Perley said:
The short answer is to define the relationship in the
dataset and have the autogenerated value returned from the
insert. If the releationship is correctly defined the
foreign key value will automatically be inserted into the
second table.
-----Original Message-----
Hi,
What i need to do is to Insert a record into a primary table and then
insert a corresponding record into the child table.My problem is that the
Primary column is an identity column so after inserting into the primary
table when i need to insert into the child table i need to know the the
primary columns value(which is auto generated by the database) and then use
this value to inert into the child table.Any one who faced this problem
earlier.
As for example how do i insert records into Northwind's Order and [Order
details] table .
Rgds,
Sudha
.