【问题标题】:Remove primary key in datatable删除数据表中的主键
【发布时间】:2011-10-23 01:46:14
【问题描述】:

有没有办法从数据表中删除主键或者有没有办法先删除“PK”的约束,然后删除列本身?

谢谢!

更新:

 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;

【问题讨论】:

  • 哪个数据库?请考虑您的标签。
  • 我在问题中提到了数据表。这意味着 asp.net 数据表
  • .NET 的 System.Data.DataTable,因为它不仅仅属于 ASP.NET。

标签: c# asp.net visual-studio datatable


【解决方案1】:

您可以使用

删除主键
DataTable.PrimaryKey = null;

您可以使用删除数据表列

DataTable.Columns.Remove("column name here");

【讨论】:

  • 这会删除列还是约束?如果稍后,那么如何删除列?
  • 谢谢!这样可行!但是,如果我再次添加它(我需要这种方式!)它会抛出“这些列当前没有唯一值”的错误。我已经用代码更新了我的问题。
  • @Xor power: 所以...这些列目前有唯一值吗?
  • @Xor power:好吧,如果您删除该列,这些值就会消失。如果您稍后重新添加该列,它会包含默认值(不是唯一的)。
【解决方案2】:

我发现有时在从 DataTable 中删除 PrimaryKey 后:

MyDataTable.PrimaryKey = null;

Unique 设置在已删除 PrimaryKey 的成员列上保持为真。

我的解决方案:

 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;
}

【讨论】:

  • 为什么会有这么长的代码?为什么不使用 foreach 作为 'foreach(DataColumn dac in LocDataTable.Columns)dac.Unique = false;'
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-07-19
  • 2014-06-24
  • 2021-06-03
  • 2011-01-07
  • 2021-02-04
相关资源
最近更新 更多