如何检查 datatable.PrimaryKey 是否设置
我有一个数据表,如果还没有主键,我必须为其分配一个主键。我尝试过:
if (ds.Tables[0].PrimaryKey == null)
{
ds.Tables[0].PrimaryKey = new DataColumn[] { dt.Columns["Naam"] };
}
但是 PrimaryKey(在本例中)不为空。当我检查它包含: {System.Data.DataColumn[0]} 我如何检查?
i have a datatable which i have to assign a primary key if it doesn't already have one. i tried :
if (ds.Tables[0].PrimaryKey == null)
{
ds.Tables[0].PrimaryKey = new DataColumn[] { dt.Columns["Naam"] };
}
But the PrimaryKey (in this case) not null. When i checked it contained : {System.Data.DataColumn[0]} How can i check on that?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
哈维尔的答案是正确的,但缺乏解释。所以这里,DataTable.PrimaryKey 属性是 DataColumn 的集合。
如果未设置 DataTable PrimaryKey 属性,则集合的长度将为 0。如果 DataTable 有一个或多个定义为主键的字段,则 PrimaryKey 属性的长度将反映这一点。
因此,像这样检查:
将告诉我们是否没有添加任何列来表示主键,并且该部分
实际上会将 DataColumn 添加到 PrimaryKey 属性持有的列的集合中。
Javier's answer is correct, but lacks explanation. So here it is, DataTable.PrimaryKey property is collection of DataColumns.
If the DataTable PrimaryKey property is not set than length of the collection will be 0. If DataTable has one or more fields defined as primary key than length of the PrimaryKey property will reflect this.
So, checking like this:
will tell us if no columns are added to represent the primary key, and the part
would actually add DataColumn(s) to collection of columns held by PrimaryKey property.
看来这并不难,毕竟我已经尝试过了,但显然做错了什么,因为当我再次尝试时它确实有效:
Looks like it is not that hard after all i already tried this but apparently did something wrong because when i just tried again it did work :