开发者

c# datatable primary key issue

开发者 https://www.devze.com 2022-12-31 16:18 出处:网络
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 pr

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.


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"    
}


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

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

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号