Retrieving AutoGenerated Id from the database

Most of us don't have to worry about how linq does all the magic in the background of persisting our objects and syncing up our primary keys that are auto generated in the database. However if you are manually creating your class it is good to know what attributes are must and required to be able to save objects to the database and how to sync the auto generated id created by the database with property defined as Primary column in the entity class. If you want to sync up primary key identity column with entity member when you insert an instance of the entity class, you have to set the column defined as Primary Key column and set the column as IsDbGenerated to true. Here is a very simple example of a datacontext and Categories class that has IsDbGenerated set to true for CategoryID column.

image

image

In the above code, I have marked my CategoryID column as primary key. This is required by linq to SQL to insert  records into the database. You must have at least one column as primary column. Secondly I am also setting IsDbGenerated to true to sync up the categoryId column with the auto generated id.

No Comments