Permalink
Fetching contributors…
Cannot retrieve contributors at this time
76 lines (59 sloc) 2.76 KB
title ms.custom ms.date ms.prod ms.reviewer ms.suite ms.technology ms.tgt_pltfrm ms.topic ms.assetid caps.latest.revision author ms.author manager
Defining Primary Keys
03/30/2017
.net-framework
dotnet-ado
article
2ea85959-e763-4669-8bd9-46a9dab894bd
4
JennieHubbard
jhubbard
jhubbard

Defining Primary Keys

A database table commonly has a column or group of columns that uniquely identifies each row in the table. This identifying column or group of columns is called the primary key.

When you identify a single xref:System.Data.DataColumn as the xref:System.Data.DataTable.PrimaryKey%2A for a xref:System.Data.DataTable, the table automatically sets the xref:System.Data.DataColumn.AllowDBNull%2A property of the column to false and the xref:System.Data.DataColumn.Unique%2A property to true. For multiple-column primary keys, only the AllowDBNull property is automatically set to false.

The PrimaryKey property of a xref:System.Data.DataTable receives as its value an array of one or more DataColumn objects, as shown in the following examples. The first example defines a single column as the primary key.

workTable.PrimaryKey = New DataColumn() {workTable.Columns("CustID")}  
  
' Or  
  
Dim columns(1) As DataColumn  
columns(0) = workTable.Columns("CustID")  
workTable.PrimaryKey = columns  
workTable.PrimaryKey = new DataColumn[] {workTable.Columns["CustID"]};  
  
// Or  
  
DataColumn[] columns = new DataColumn[1];  
columns[0] = workTable.Columns["CustID"];  
workTable.PrimaryKey = columns;  

The following example defines two columns as a primary key.

workTable.PrimaryKey = New DataColumn() {workTable.Columns("CustLName"), _  
                                         workTable.Columns("CustFName")}  
  
' Or  
  
Dim keyColumn(2) As DataColumn  
keyColumn(0) = workTable.Columns("CustLName")  
keyColumn(1) = workTable.Columns("CustFName")  
workTable.PrimaryKey = keyColumn  
workTable.PrimaryKey = new DataColumn[] {workTable.Columns["CustLName"],   
                                         workTable.Columns["CustFName"]};  
  
// Or  
  
DataColumn[] keyColumn = new DataColumn[2];  
keyColumn[0] = workTable.Columns["CustLName"];  
keyColumn[1] = workTable.Columns["CustFName"];  
workTable.PrimaryKey = keyColumn;  

See Also

xref:System.Data.DataTable
DataTable Schema Definition
DataTables
ADO.NET Managed Providers and DataSet Developer Center