1

A lot of example of code-first shows that the PK of the table is XXXXXID, if the XXXXX matches the entity name; otherwise the ORM will create the PK using the columns ending with "ID". (Maybe it will create combined key for many-to-many relationship).

What if the entity already have a natural key? Maybe code first should be avoid if a sound database design is required?

ca9163d9
  • 27,283
  • 64
  • 210
  • 413
  • 1
    I'd hardly call it a new trend - ever since MS Access offered to add a primary key if you didn't define one, and did so by creating a column called ID using a sequence, a lot of people have thought that the two concepts are synonymous. – Damien_The_Unbeliever Jun 20 '12 at 06:32
  • 1
    If your table **really** has a good, natural key (that is narrow, unique, stable) - then by all means, use it. And EF code-first doesn't make this impossible - not at all. [You can easily decorate such a given property with the `[Key]` attribute](http://msdn.microsoft.com/en-us/data/gg193958.aspx) to mark it as the primary key of an entity. – marc_s Jun 20 '12 at 06:52

1 Answers1

2

As @marc_s described in the comment you can use your own key (even composite) but you must remember that EF is little bit more restrictive for key usage. You cannot change PK value for existing entity - the key in EF is immutable. The only time when you can define value for PK is before you insert it to the database.

Community
  • 1
  • 1
Ladislav Mrnka
  • 360,892
  • 59
  • 660
  • 670