Get Primary Key column values after bulk insertion using SqlBulkCopy

c# sql sqlbulkcopy sql-server

Question

Can anyone help me how to get the column values of a Primary Key column after bulk insertion?

I am using SqlBulkCopy to insert multiple rows at a time into table(say Table 1). I need the ids of a column MsgId(PK) from Table 1 once the rows get inserted. I need to use these ids which is the foreign key in another table Table 2

Here is my code,

        DataTable dtMessageDetails = new DataTable("Message Details");
        SqlBulkCopy copier = new SqlBulkCopy(Connectionstring);
        copier.DestinationTableName = "Table 1";
        copier.WriteToServer(dtMessageDetails);

Accepted Answer

Lock the table before you insert your bulk. You know the number of rows and if you select the last id, knowing the total number of elements, then you will know their IDs.



Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Is this KB legal? Yes, learn why