[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 645
  • Last Modified:

Creating primary key on DataTable


In the following code why does the author create a unique constraint and a primary key on the same column? If you wanna make a column the primary key one, then obviously every value will be unique right? and also....why is there a need for the array? i thought only the last line would be sufficient

DataColumn[]  pk = new DataColumn[1] ;
pk[0] = dt.Columns["ProductID"] ;

dt.Constraints.Add ( new UniqueConstraint ( "PK_Products" , pk[0] ) ) ;

dt.PrimaryKey = pk ;
  • 2
2 Solutions
Mohammed NasmanSoftware DeveloperCommented:

  You could write the previous code as one sentence like

dt.Constraints.Add(new UniqueConstraint("PK_Products", dt.Columns[0] ,true) ) ;

You need to use array of DataColumn, when you would to create combined primay key, from two fields or more
dt.Constraints.Add ( new UniqueConstraint ( "PK_Products" , pk[0] ) ) ; is superfluous as when you set it as a PrimaryKey, it is marked as Unique, Not Nullable (AllowDBNull is false)
The only time where it makes sense is if the primary key is a composite key itself. Then You'd have to set the settings manually in each column

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now