tags:

views:

316

answers:

2

So I have a table in an Oracle database that I'm basically trying to replicate in C# along with its primary key. I can load the table just fine, but then when I try to add the same primary key constraint as the oracle table, I get this error :

"These columns don't currently have unique values".

Here's the code

DataTable dt = new DataTable(combine(owner, name));
string q = "select " + getColumnSelect(owner, name) + 
           " from " + combine(owner, name) + " " + 
           (where_clause ?? "") + " order by " + getOrderByKeys(owner, name);

// load the data table
OracleDataAdapter oda = new OracleDataAdapter(q, conn);
oda.FillLoadOption = LoadOption.PreserveChanges;
dt.BeginLoadData();
oda.Fill(dt);
dt.EndLoadData();

// now set primary keys
List<DataColumn> cols = new List<DataColumn>();
foreach (string key in getKeys(owner, name))
{
    cols.Add(dt.Columns[key]);
}


// This is where it fails
dt.PrimaryKey = cols.ToArray();

return dt;

Now using the exact same select statement.. if I add the primary key to the datatable before I fill it, it works just fine. I'm stumped.

EDIT: I forgot to add that this works with the same table (different data of course) on another database. And I verified that the data in the non-working database is unique.

A: 

What does getKeys(owner, name) return when you have not added the PK in the database ?

I'm going to guess --- nothing... .

Charles Bretana
It returns the primary key correctly. I set a breakpoint there because I thought that might be the problem.
climbage
+1  A: 

Check for whitespace, here's a sample that has unique values (but one has a space) that will recreate the issue:

DataTable dt = new DataTable("Hello world");
dt.Columns.Add("Col1");
dt.Rows.Add("Val1");
dt.Rows.Add("Val1 ");
dt.Rows.Add("Val3");
List<DataColumn> cols = new List<DataColumn>();

cols.Add(dt.Columns["Col1"]); 

try
{
    dt.PrimaryKey = cols.ToArray();
}
catch (Exception e)
{
    // Throws "These columns don't currently have unique values"    
}
GalacticJello
Good catch. This is indeed the issue. Looks like I'll be filling the datatable manually instead.
climbage