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 ...

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

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.