3not3
3not3

Reputation: 536

"[Key]" attribute supposed to set the column as primary but its not, EF code first approach

Shouldn't [Key] attribute sets the database field as primary key ? I have a class already defined, later when I tried to set the primary key by putting [Key] attribute, the Add-migration command does not show any changes in up() or down() method. So does it means primary key has to be declared at the beginning and cannot be changed ?

I tried to create a test class {id,name} with no primary key, once the database was updated, later when tried setting the id field as primary key its not seeing the change in Add-Migration, what I'm missing ?

Upvotes: 1

Views: 874

Answers (1)

DavidG
DavidG

Reputation: 118937

By convention, Entity Framework decides a primary key property if you don't tell it which one to use. In order, this is how it chooses:

  1. If you have a property called Id.
  2. If you have a property called ClassNameId (i.e. your class is Book, the property will be BookId.)
  3. Any property (or multiple properties for a compound key) that have the [Key] attribute.

And all of this can be overridden in the OnModelCreating method of your context.

So what has happened for you is that your existing Id property was already chosen as a primary key and adding the attribute makes no difference.

See the docs for more information on how this works.

Upvotes: 1

Related Questions