is there a way to remove primary key from the datatable Or is there any way to remove the constraints of "PK" first and then remove the column itself?
Thanks!
UPDATED:
dtTable.Columns.Add(new System.Data.DataColumn("PRIMARY_KEY", typeof(System.Int32)));
dtTable.PrimaryKey = new DataColumn[1] { dtTable.Columns["PRIMARY_KEY"] }; // throws an error
dtTable.Columns["PRIMARY_KEY"].AutoIncrement = true;
This identifying column or group of columns is called the primary key. When you identify a single DataColumn as the PrimaryKey for a DataTable, the table automatically sets the AllowDBNull property of the column to false and the Unique property to true.
Ok this is more clear now: You can't remove constraints, they are disable during merge operation and then automatically enable after the merge if they can be enabled. As the error is like after the merge operation is completed, the Constraints can't be enabled due to some of the invalid values in target datatable.
The primary key for a table is set by specifying an array of DataColumn objects from the table. The following example illustrates creating a primary key based on two columns: // set the primary key based on two columns in the DataTable DataTable dt = new DataTable("MyTable"); dt. Columns.
You can remove primay key using
DataTable.PrimaryKey = null;
you can delete data table column using
DataTable.Columns.Remove("column name here");
I found that sometimes after removing PrimaryKey from a DataTable:
MyDataTable.PrimaryKey = null;
the Unique setting remains true on the member columns of the deleted PrimaryKey.
My solution:
public static void KillPrimaryKey(DataTable LocDataTable)
{
int LocPriKeyCount = LocDataTable.PrimaryKey.Length;
string[] PrevPriColumns = new string[LocPriKeyCount];
// 1. Store ColumnNames in a string Array
for (int ii = 0; ii < LocPriKeyCount; ii++) PrevPriColumns[ii] = LocDataTable.PrimaryKey[ii].ColumnName;
// 2. Clear PrimaryKey
LocDataTable.PrimaryKey = null;
// 3. Clear Unique settings
for (int ii = 0; ii < LocPriKeyCount; ii++) LocDataTable.Columns[PrevPriColumns[ii]].Unique = false;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With