views:

455

answers:

1

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

+2  A: 

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.

Michael Haren
try { UniqueConstraint uc = new UniqueConstraint("pk",pks, true); dtbl.Constraints.Add(uc); }I checked HasErrors and its false after each table has their PK applied. (checked the Dataset and DataTable properties).... I even call AcceptChanges()...
WIDBA
The dataset gets filled from the datasource, and then I apply the keys.. is there some property on the dataset that I need to set to enable the constraints?
WIDBA
can you insert a duplicate *after* the primary key is applied?
Michael Haren
working on doing building the dataset schema - then apply the keys - then load data to try that out...
WIDBA
I used Fill_Schema first, applied the PKs and then do the fill and its throwing an exception - thanks...
WIDBA
Great, glad it's "working" now. Too bad you had to do all that rework.
Michael Haren