Sunday 2 September 2012

Entity Framework 5: auto generated GUID as primary key

If you are using Entity Framework 5 - Code First and want to create an auto generated GUID as primary key, you have two options.

Consider the following POCO class:
public class Album
{
    public Guid ID { get; set; }
    public DateTime DateCreated { get; set; }
}
1) Data Annotations
Decorate your Primary Key with DatabaseGenerated / DatabaseGenerationOption.Identity.

[DatabaseGenerated(DatabaseGenerationOption.Identity)]
public Guid ID { get; set; }
Note: you can also use the "Key" attribute, but since the name of my property is ID Entity Framework will automatically detect that this field is a primary key.

2) Fluent API
In your DbContext class, override the OnModelCreating method and add the following line:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<Album>().Property(p => p.ID).HasDatabaseGeneratedOption(DatabaseGeneratedOption.Identity);
}

1 comment:

  1. Will it be "DatabaseGenerationOption" or "DatabaseGeneratedOption" ?

    ReplyDelete