I have two DataTables A and B. A is the parent table. Rows in B contain a field ParentId that references A.
I want to bulk insert A and B separately. After inserting A, how do I set the ParentId in the corresponding child rows in B?
Update:
I have the following code for creating the DataTables:
var a= new DataTable("A");
DataColumn id= new DataColumn("Id", typeof(int));
billablePriceMapId.AutoIncrement = true;
billable.Columns.Add(id);
DataColumn fee = new DataColumn("Fee", typeof(decimal));
billable.Columns.Add(fee);
DataColumn[] keys = new DataColumn[1];
keys[0] = id;
billable.PrimaryKey = keys;
For the child table:
var b= new DataTable("B");
DataColumn id= new DataColumn("Id", typeof(int));
billablePriceMapId.AutoIncrement = true;
billable.Columns.Add(id);
DataColumn parentId= new DataColumn("ParentId", typeof(int));
billable.Columns.Add(parentId);
DataColumn[] keys = new DataColumn[1];
keys[0] = id;
billable.PrimaryKey = keys;
I have not set up any relationship between the two tables. I would like to know how I could do that the right way.
Following is the code that I use for bulk insert:
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(connection, SqlBulkCopyOptions.Default, transaction))
{
try
{
bulkCopy.DestinationTableName = "dbo.A";
bulkCopy.WriteToServer(a);
bulkCopy.DestinationTableName = "dbo.B";
bulkCopy.WriteToServer(b);
}
catch (Exception ex)
{
Logger.Error(ex, "Bulk copy operation failed.");
}
}
A
's primary key is anIDENTITY
column, correct? Do you have the ID's that should be inserted or do you want to let the database generate them fo you? – Tim Schmelter Sep 13 '18 at 11:21