Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we have table without primary key in entity framework?

I was just practicing code first new database entity framework from msdn, I wanna know whether a table without primary key can be created in code first new database EF?

like image 950
Prateek Avatar asked Mar 13 '13 09:03

Prateek


People also ask

Can Entity Framework work without primary key?

Because Entity Framework is able to modify data in your database it needs a primary key to be defined in order for it to be able to uniquely identify rows.

Can a table be without 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.

How do you use a table which is not having a primary key in Entity Framework?

The table/view TABLE_NAME does not have a primary key defined and no valid primary key could be inferred. This table/view has been excluded. To use the entity, you will need to review your schema, add the correct keys, and uncomment it.

Can a table only have a primary key?

The PRIMARY KEY constraint uniquely identifies each record in a table. Primary keys must contain UNIQUE values, and cannot contain NULL values. A table can have only ONE primary key; and in the table, this primary key can consist of single or multiple columns (fields).


2 Answers

There is a great difference between what EF can do with a database, and what is possible with a database.

Most databases allow for a table to be without a primary key. Most databases also allow for a table to be without a clustered index / Index Organized Table (or what ever it is the specific term for it in other database systems).

There is nothing wrong with that, and one should not state that it is a bad idea to have a table without a PK.

As always, it dependes on the needs and usage of the specific table. e.g. a log table, does not need a PK. It will never be used as a FK, so what is it use?

Bottom line, EF does not support tables without a key out of the box, there are some weird workarounds, but none that I have seen is good enough. That is a shame.

like image 81
sirpadk Avatar answered Sep 21 '22 10:09

sirpadk


No you can't because Entity Framework needs to know the key to keep track on the object when you make an update or delete operation.

Anyway it's not a good idea to have a table without a PrimaryKey

like image 41
Wahid Bitar Avatar answered Sep 19 '22 10:09

Wahid Bitar