O'Reilly logo

ADO.NET in a Nutshell by Bill Hamilton, Matthew MacDonald

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

The UniqueConstraint

The UniqueConstraint prevents duplication in a single column or the combined value of a group of columns. The UniqueConstraint object adds two properties: Columns, which defines one or more DataColumn objects that, when taken together, must be unique; and IsPrimaryKey, which indicates whether the UniqueConstraint is required to guarantee the integrity of the primary key for the table.

The UniqueConstraint provides several overloaded constructors. Here’s how you might create a UniqueConstraint that prevents duplicate CustomerID values:

// Create the UniqueConstraint object.

UniqueConstraint uc = new UniqueConstraint("ID", dt.Columns["CustomerID"]);



// Add the UniqueConstraint to the table's Constraints collection.

dt.Constraints.Add(uc);

You can also define a UniqueConstraint that encompasses several columns, such as this first and last name combination:

// Create an array with the two columns.

DataColumn[] cols = new DataColumn[] {dt.Columns["LastName"],  

  dt.Columns["FirstName"]};



// Create the UniqueConstraint object.

UniqueConstraint uc = new UniqueConstraint("FullName", cols);



// Add the UniqueConstraint to the table's Constraints collection.

dt.Constraints.Add(uc);

To create a primary key UniqueConstraint, use an overloaded version of the constructor that accepts a Boolean parameter, and specify true. Once created, you can’t change the IsPrimaryKey property of a UniqueConstraint.

// Create a UniqueConstraint object that represents the primary key. UniqueConstraint ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required