Reputation: 536
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
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:
Id
.ClassNameId
(i.e. your class is Book
, the property will be BookId
.)[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