How to mark identity column properly with Entity Framework 6.1?

.net .net-4.6 entity-framework entity-framework-6 sql-server


I've seen many posts and answers regarding how to mark a field as the identity column. Many of them are outdated and are targeting older versions of Entity Framework.

Some resources tell me to use an attribute on the field:

public int ID { get; set; }

Other resources tell me to add this code to OnModelCreating method:

modelBuilder.Entity<User>().Property(u => u.ID).HasDatabaseGeneratedOption(System.ComponentModel.DataAnnotations.Schema.DatabaseGeneratedOption.Identity);

Which one should I use? First, second, both, doesn't matter, or something else?

11/26/2015 8:02:28 PM

Accepted Answer

As long as the type of the primary key property is numeric or GUID, Code First will, by convention, automatically configure the key as an identity column.

That means you don't need to have any of the configuration you put in your code to explicity set the property as an identity column because Code First already use covention for that. The data annotation attribute or fluent API configurations you set are useless.

You use those configurations on numeric or GUID type primary key only if you want to disable the identity.

11/26/2015 8:14:31 PM

Popular Answer

This is for those who lost more than two hours on this issue.

I made a mistake by marking a column as KEY that later I realize it was not the key, but just a column.

My model had dependencies, so I could not just remove the KEY attribute and let it be. The default Id column never got as identity column at SQL Server, either after generating the corresponding migration and setting: identity as true.

Instead, I had to remove the Dbset from context, remove all references to it and from it in other entities. And generate a migration that drops the table, then fixing the model.. make sure it was OK. And then generating the well done model, plugging in all dependencies back.

It was my mistake on the first hand. So I have no body to blame but myself.

Hope no one come to this situation again, but if do happens, this what I did.

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow