Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Table doesn't have a primary key

Tags:

c#

mysql

asp.net

i get the following exception (missing primary key) in the line of using Find() method

"Table doesn't have a primary key."

I've rechecked the Database and all Primary Key columns are set correctly.

my code:

DataTable dt = p.GetAllPhotos(int.Parse(Id));
DataTable temp = new DataTable();
temp = dt.Clone();
temp = (DataTable)(Session["currentImage"]);
DataTable dtvalid = new DataTable();
dtvalid = dt.Clone();
DataRow[] drr = new DataRow[1];
drr[0] = dt.Rows.Find((int.Parse(temp.Rows[0]["photoId"].ToString()))+1);
foreach (DataRow dr in drr)
{
    dtvalid.ImportRow(dr);
}
dtvalid.AcceptChanges();'
like image 935
Anyname Donotcare Avatar asked Aug 25 '10 15:08

Anyname Donotcare


People also ask

What if a table does not have primary key?

Every table can have (but does not have to have) a primary key. The column or columns defined as the primary key ensure uniqueness in the table; no two rows can have the same key. The primary key of one table may also help to identify records in other tables, and be part of the second table's primary key.

Can an entity have no primary key?

Every entity in the data model must have a primary key whose values uniquely identify instances of the entity.

Can a table have foreign key but no primary key?

Yes, you can make one without a Primary Key (or, another option is a Compound Primary Key - making the two references a unique pair, and using that as the unique identifying key - but even this isn't necessary (note: just because it "isn't necessary" doesn't mean it isn't "good practice"; it wouldn't generally be a ...

Can a table only have a primary key?

Each table can only have one primary key. Access can automatically create a primary key field for you when you create a table, or you can specify the fields that you want to use as the primary key.


1 Answers

You need to set the PrimaryKey property of your DataTable object before you call Find

DataColumn[] keyColumns = new DataColumn[1];
keyColumns[0] = dt.Columns["<columnname>"];
dt.PrimaryKey = keyColumns;
like image 55
Crispy Avatar answered Sep 17 '22 01:09

Crispy