In many cases, we need to know what the table's primary key is. In ADO. net, datatable can be used to map tables in the database. So you can use the properties of the datatable
Primarykey , It is
Datacolumn [] Type is an array. We can use the following Code
Datacolumn [] Cols;
Cols = Table. primarykey;
// Note that not Cols is a datacolumn array, not a datacolumn variable. In this way, it is mainly used to deal with the problem of joint primary keys.
For ( Int I = 0 ; I < Cols. length; I ++ )
{
MessageBox. Show (Cols [I]. columnname );
}
This problem has been solved, but cols. length is 0. When the datatable is filled by default, no primary key information is obtained from the database. How to obtain the primary key? After research, we found that when filling dataset, we can use the missingschemaaction attribute of dataadapter to solve this problem, so we have the following code:
// Use dataadapter to fill the datatable
Dataadapter. missingschemaaction = Missingschemaaction. addwithkey;
Dataadapter. Fill (table );
Datacolumn [] Cols;
Cols = Table. primarykey;
// Note that not Cols is a datacolumn array, not a datacolumn variable. In this way, it is mainly used to deal with the problem of joint primary keys.
For ( Int I = 0 ; I < Cols. length; I ++ )
{
MessageBox. Show (Cols [I]. columnname );
}
in this way, we can get what we want. The missingschemaaction attribute is the operation to be performed when the existing dataset (or datatable) architecture does not match the imported data. Missingschemaaction. addwithkey is an enumeration value. It is used to add required columns and primary key information to complete the architecture. You can explicitly set primary key constraints on each able.