Creating AutoIncrement Columns

ADO.NET supports columns that increment automatically to ensure that values are unique when new rows are added to the table. These properties are AutoIncrement, AutoIncrementSeed, and AutoIncrementStep. The following code demonstrates creation of an AutoIncrement column:

DataColumn col = new DataColumn("Id", typeof(System.Int32));

col.AutoIncrement = true;

col.AutoIncrementSeed = -1;

col.AutoIncrementStep = -1;

The code uses seed and step values of -1. This causes the values for the added rows to start at -1, with subsequent values of -2, -3, and so on, which ensures that the automatically generated values will not already exist in a data source with an AutoIncrement key containing only positive values. When the data is updated back to the data source, the added records are correctly identified as new records, inserted into the data source, and at that point the AutoIncrement value can be returned from the data source and update the negative value in the DataSet. Returning the AutoIncrement values generated from the data source is discussed in more detail in Chapter 15.

Get ADO.NET in a Nutshell now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.