Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UNIQUE constraint on DataTable

Can I have a clustered key on DataTable in C# ?

There's a requirement in my code to have constraints for possible combinations of 3 columns to be unique .....

like image 526
nirav Avatar asked Sep 14 '25 09:09

nirav


1 Answers

What you need is really a unique constraint on your DataTable. Clustered keys are a SQL Server on-disk feature and not applicable to a DataTable.

Check out MSDN doc on DataTable constraints:

The UniqueConstraint object, which can be assigned either to a single column or to an array of columns in a DataTable, ensures that all data in the specified column or columns is unique per row. You can create a unique constraint for a column or array of columns by using the UniqueConstraint constructor.

So try something like this:

// this is your DataTable
DataTable custTable ;

// create a UniqueConstraint instance and set its columns that should make up
// that uniqueness constraint - in your case, that would be a set of *three*
// columns, obviously! Adapt to your needs!
UniqueConstraint custUnique = 
   new UniqueConstraint(new DataColumn[] { custTable.Columns["CustomerID"], 
                                           custTable.Columns["CompanyName"] });

// add unique constraint to the list of constraints for your DataTable
custTable.Constraints.Add(custUnique);

And that should do the trick for you!

like image 107
marc_s Avatar answered Sep 17 '25 01:09

marc_s