Прочитать на английском

Поделиться через


DataTable.PrimaryKey Свойство

Определение

Возвращает или задает массив столбцов, которые являются столбцами первичного ключа для таблицы данных.

[System.ComponentModel.TypeConverter(typeof(System.Data.PrimaryKeyTypeConverter))]
public System.Data.DataColumn[] PrimaryKey { get; set; }
public System.Data.DataColumn[] PrimaryKey { get; set; }
[System.ComponentModel.TypeConverter(typeof(System.Data.PrimaryKeyTypeConverter))]
[System.Data.DataSysDescription("DataTablePrimaryKeyDescr")]
public System.Data.DataColumn[] PrimaryKey { get; set; }

Значение свойства

Массив объектов DataColumn.

Атрибуты

Исключения

Ключ является внешним ключом.

Примеры

В первом примере показано, как вернуть столбцы первичного ключа для , отображаемого DataTableDataGridв . Во втором примере показано, как задать столбцы первичного ключа для DataTable.

private void GetPrimaryKeys(DataTable table)
{
    // Create the array for the columns.
    DataColumn[] columns;
    columns = table.PrimaryKey;

    // Get the number of elements in the array.
    Console.WriteLine($"Column Count: {columns.Length}");
    for (int i = 0; i < columns.Length; i++)
    {
        Console.WriteLine($"{columns[i].ColumnName} {columns[i].DataType}");
    }
}

private void SetPrimaryKeys()
{
    // Create a new DataTable and set two DataColumn objects as primary keys.
    var table = new DataTable();
    var keys = new DataColumn[2];
    DataColumn column;

    // Create column 1.
    column = new DataColumn();
    column.DataType = Type.GetType("System.String");
    column.ColumnName= "FirstName";

    // Add the column to the DataTable.Columns collection.
    table.Columns.Add(column);

    // Add the column to the array.
    keys[0] = column;

    // Create column 2 and add it to the array.
    column = new DataColumn();
    column.DataType = Type.GetType("System.String");
    column.ColumnName = "LastName";
    table.Columns.Add(column);

    // Add the column to the array.
    keys[1] = column;

    // Set the PrimaryKeys property to the array.
    table.PrimaryKey = keys;
}

Комментарии

Первичный ключ таблицы должен быть уникальным для идентификации записи в таблице. Кроме того, можно создать таблицу с первичным ключом, состоящей из двух или более столбцов. Это происходит, когда один столбец не может содержать достаточно уникальных значений. Например, первичный ключ из двух столбцов может состоять из столбцов OrderNumber и ProductID. Так как первичные ключи могут состоять из нескольких столбцов, PrimaryKey свойство состоит из массива DataColumn объектов .

Применяется к

Продукт Версии
.NET Core 2.0, Core 2.1, Core 2.2, Core 3.0, Core 3.1, 5, 6, 7, 8, 9
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0, 2.1

См. также раздел