我有一个datatable,如果它还没有主键,我必须给它分配一个主键。我试过了:
if (ds.Tables[0].PrimaryKey == null)
{
ds.Tables[0].PrimaryKey = new DataColumn[] { dt.Columns["Naam"] };
}但是PrimaryKey (在本例中)不为空。当我检查它包含:{System.Data.DataColumn}我如何检查它?
发布于 2017-06-10 01:54:37
哈维尔的答案是正确的,但缺乏解释。这里,DataTable.PrimaryKey属性是DataColumns的集合。如果未设置DataTable PrimaryKey属性,则集合的长度将为0。如果DataTable有一个或多个字段定义为主键,则PrimaryKey属性的长度将反映这一点。所以,像这样检查:
if (ds.Tables[0].PrimaryKey.Length == 0)将告诉我们是否没有添加任何列来表示主键,并且部分
ds.Tables[0].PrimaryKey = new DataColumn[] { dt.Columns["Naam"] }; 实际上会将DataColumn添加到由PrimaryKey属性持有的列集合中。
https://stackoverflow.com/questions/5911209
复制相似问题