简体   繁体   English

.net数据集主键 - 强制执行唯一性?

[英].net Dataset Primary-Keys - enforcing uniqueness?

I have a small dataset with a few datatables. 我有一个带有一些数据表的小数据集。 I load the datatables from various DBs and have a config file that I read to determine the primary keys I want to enforce on the given datatables. 我从各种DB加载数据表,并有一个我读取的配置文件,以确定我想在给定的数据表上强制执行的主键。 If the config doesn't contain a proper (non unique) primary key, how can I catch this event when applying the primary key to the datatable? 如果配置不包含正确的(非唯一的)主键,那么在将主键应用于数据表时如何捕获此事件? Currently it appears that it allows me to apply the primary key, even though it is not unique.... 目前它似乎允许我应用主键,即使它不是唯一的....

       DataTable dtbl = ds.Tables[t.tblname];

       DataColumn[] pks = new DataColumn[t.Get_Key_Columns().Count];
       int i = 0;
        foreach(DataColumn c in dtbl.Columns)
        {
            if(t.Get_Key_Columns().Exists(delegate(App_Column ac) 
                  {return (ac.column_name == c.ColumnName);}))
            {
                pks[i] = c;
                i++;
            }
        }
        try
        {
            dtbl.PrimaryKey = pks; 
        } 
         catch etc.......

Anyone point out what I am missing? 有人指出我错过了什么? Thanks 谢谢

How about adding them as a constraint? 如何将它们添加为约束?

dt.Constraints.Add("PKC", Columns, true)

If that still allows duplicates, does the .HasErrors property provide any indication? 如果仍然允许重复,.HasErrors属性是否提供任何指示?


Edit from the comments: 从评论中编辑

What ultimately worked for OP was this work-around: add the constraints before filling the table. 最终适用于OP的是这种解决方法: 填充表格之前添加约束。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM