C# Tips

C# Tip Article

Using Identity column in EF7 (VS 2015 ASP.NET 5)

Visual Studio 2015 (RTM) provides ASP.NET 5 Preview Template and this project template includes Entity Framework 7.0 (EF7, 7.0.0-beta5) by default. One of noticeable changes in EF7 is Identity key column.

Prior to EF7 - when used against SQL Server - if a key column has [DatabaseGenerated(DatabaseGeneratedOption.Identity)] attribute, EF used Identity column in SQL Server. EF7 now uses SEQUENCE of SQL Server instead of Identity.

SEQUENCE was first introduced in SQL Server 2012. Sequences, unlike identity columns, are not associated with specific tables. It is a user-defined schema bound object that generates a sequence of numeric values. The sequence value can be generated in an ascending or descending order at a defined interval and can be configured to restart (cycle) when exhausted.

So it is a good change in EF7, but if we have existing tables with Identity column, what should we do? In order to use Identity instead of Sequence, we have to call UseIdentity() method for the identity property in OnModelCreating().

public class NewsDbContext : DbContext
{
	//....
	
	protected override void OnConfiguring(EntityOptionsBuilder optionsBuilder)
	{		
		optionsBuilder.UseSqlServer(connStr);
	}

	protected override void OnModelCreating(ModelBuilder modelBuilder)
	{
		modelBuilder.Entity<Customer>(p =>
		{                
		    // Call UseIdentity() for Id property
			p.Property(e => e.Id).ForSqlServer().UseIdentity();
		});
	}
	public DbSet<Customer> Customers { get; set; }
}

public class Customer
{
	[Key]
	[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
	public long Id { get; set; }
	
	//... (others) ...
}

In the example code above, Customer entity has Id property whose attribute is DatabaseGeneratedOption.Identity. Assuming that the Id column is an identity column in the table, we need to call .ForSqlServer().UseIdentity() for the Id property in OnModelCreating(),