I've already covered the practical advantages 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 MySQL, Microsoft 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:
1 2 3 4 5 |
public class Item { [DatabaseGenerated(DatabaseGeneratedOption.Identity)] public Guid ID { get; set; } } |
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!
GUID IS NOT A NUMERIC FIELD AND IS NOT AUTO-INCREMENT
and [databasegenerated.identity] just tells EF that the content of the field will be generated by the database engine on insert.
Use sequential guid if you want an id to auto-increment