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?

2
  • 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. Jun 20, 2012 at 6: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 to mark it as the primary key of an entity.
    – marc_s
    Jun 20, 2012 at 6:52

1 Answer 1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.