The Cloud One Blog

Posted by admin on Monday, February 6, 2017

How to disable Identity for int primary keys in Code-First

How to disable Identity for int primary keys in Code-First

EF Code-First uses conventions to beautifully create identity field for us when defining int primary keys. However, there are times that we don't want the database generate the primary key values for us. Here are two ways to avoid Code-First set identity fields on int primary keys.

Using data annotation:

public class Customer

{

[DatabaseGenerated(DatabaseGeneratedOption.None)]

public int CustomerID { get; set; }

}

Using fluent API:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.Entity<Customer>().Property(c => c.CustomerID).HasDatabaseGeneratedOption(null);
base.OnModelCreating(modelBuilder);
}