Entity Framework Code-First: how to generate an auto-increment ID field

Abilitare e disabilitare il Lazy Loading con Entity Framework

I’ve already covered the practical advantage of the code-first approach featured by Entity Framework 6 in a previous post: the key concept there was all about creating the whole data model  starting from some very standard C# classes: namely, the Entities. The most frequent question asked by readers was: how to define an auto-increment Id field (or primary key) of an Entity? In other words, how can we tell the DB to assign an unique, incremental id number to each and every record by its own?

The answer is quite simple, as long as you’re using MySQLMicrosoft SQL or any other Entity Framework compatible DBMS featuring a native auto-incremental numeric fields support: all we can do is to tell the Entity Framework to properly generate it.

In order to do so we just need to use the DatabaseGeneratedAttribute in the following way:

The ID field will then be set as auto-incremental during the DB generation phase, granting a table-unique ID to each Item record.

That’s about it. Happy coding!



About Ryan

IT Project Manager, Web Interface Architect and Lead Developer for many high-traffic web sites & services hosted in Italy and Europe. Since 2010 it's also a lead designer for many App and games for Android, iOS and Windows Phone mobile devices for a number of italian companies.

View all posts by Ryan