简体   繁体   中英

.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. 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?


Edit from the comments:

What ultimately worked for OP was this work-around: add the constraints before filling the table.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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