Monday, August 16, 2010

Linq-to-SQL and Identity Columns

I recently had a situation where I had to insert records into a db table. The table had an identity column but no primary key (go figure). This presented hurdle 1 of how to insert the records since linq-to-sql's standard approach of creating a new table item, populating the fields and then inserting the new record only works if your table has a primary key.

Hurdle 1 was overcome by creating a dynamic SQL statement and using ExecuteQuery. This was fine until I had to retrieve the ID of the record that was just inserted (Hurdle #2). appending select scope_identity() after my insert statement was not playing nicely. If I specified the ExecuteQuery to be of type I would receive "Specified cast not valid". If I specified the ExecuteQuery to be of type the identity column was 0.

I overcame hurdle #2 with the following:
1) specified the ExecuteQuery to be of type
2) generated the following SQL Statement: "; select * from where = (select scope_identity())"

This returned a full record from the table with the correct value in the identityColumn property