To get the primary key of a table through a DataTable

Source: Internet
Author: User
Tags arrays key variables

In many cases we need to know what the primary key of the table is. A table in Ado.net that a DataTable can map a database is provided. You can then take advantage of the DataTable's property PrimaryKey, which is the datacolumn[] type is an array. We can use the following code

Datacolumn[] cols;
cols = Table.primarykey;
Note that not cols are DataColumn arrays, not DataColumn variables. This is done primarily to address the problem of federated primary keys.
for (int i = 0; i < cols. Length; i++)
{
MessageBox.Show (Cols[i]. ColumnName);
}

The question has been settled, but cols. Length is 0. There was no information from the primary key that was taken from the database when the DataTable was populated by default. How do I get a primary key? The study found that when populating a dataset, you can use the DataAdapter MissingSchemaAction attribute to help us solve the problem, so we have the following code:

Populating a DataTable with DataAdapter
DataAdapter. MissingSchemaAction = MissingSchemaAction.AddWithKey;
DataAdapter. Fill (Table);

Datacolumn[] cols;
cols = Table.primarykey;
Note that not cols are DataColumn arrays, not DataColumn variables. This is done primarily to address the problem of federated primary keys.
for (int i = 0; i < cols. Length; i++)
{
MessageBox.Show (Cols[i]. ColumnName);
}

So we can get what we want. The MissingSchemaAction property is the action that needs to be performed to determine if an existing dataset (or DataTable) schema does not match the incoming data. MissingSchemaAction.AddWithKey is an enumeration value that is used to add the necessary column and primary key information to complete the schema, which allows the user to explicitly set the PRIMARY KEY constraint on each DataTable.



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.