Use ExecuteScalar to insert a database row and return the primary key
I suspect that just about every developer who has had to work with SQL Server has faced this issue. You need to insert a bunch of related records, some of which depend on other records being in the database first. I stumbled on a way to use ExecuteScalar to insert a database row and return the primary key with one call.
To do this, you just add this to the end of your INSERT statement:
SELECT Scope_Identity(); |
This SQL Server function returns the primary key of the last row that was added to the database with a primary key column. For my instance, I have a SqlText class that encapsulates a lot of the System.Data.Client functionality, so my code looks like this. (I have omitted most of the fields so that this code would be shorter.)
// table 'BillingAddresses' has an integer primary key, auto generated, identity // 'addressLine1' below refers to a string variable containing line 1 of the address var sqlString = "insert into BillingAddresses (Line1) values (@Line1); SELECT Scope_Identity();"; var newBillingAddressID = SqlText.ExecuteScalar(sqlString, new { Line1 = addressLine1 }); |
However, if you are using the standard System.Data.Client namespace, your code would then look like this:
// table 'BillingAddresses' has an integer primary key, auto generated, identity // 'conn' below refers to an opened instance of a SqlConnection // 'addressLine1' below refers to a string variable containing line 1 of the address var sqlString = "insert into BillingAddresses (Line1) values (@Line1); SELECT Scope_Identity();"; SqlCommand cmd = new SqlCommand(sql, conn); cmd.Parameters.Add("@Line1", SqlDbType.VarChar); cmd.Parameters["@Line1"].Value = addressLine1; var newBillingAddressID = cmd.ExecuteScalar(); |