How to use Identity column in EF7

By FoxLearn 11/10/2024 1:58:52 AM   22
In Entity Framework 7 (EF7), the concept of an "Identity" column is typically handled through migrations and the use of the ValueGeneratedOnAdd() method in the Fluent API or the Key attribute in your model class.

In Visual Studio 2015 (RTM), the ASP.NET 5 Preview Template includes Entity Framework 7.0 (EF7). A key change introduced in EF7 is the handling of the Identity key column, which is used for auto-incrementing primary keys in the database. This change simplifies the way EF7 handles identity columns, making it easier to work with auto-generated primary keys in database tables.

Prior to EF7, when used with SQL Server, if a key column had the `[DatabaseGenerated(DatabaseGeneratedOption.Identity)]` attribute, EF would use an Identity column in SQL Server for auto-incrementing values. However, in EF7, the behavior has changed: EF now uses a SEQUENCE in SQL Server instead of the traditional Identity column for generating values for key columns. This change provides more flexibility in how auto-incrementing values are handled in the database.

SEQUENCE was first introduced in SQL Server 2012. Unlike identity columns, which are tied to specific tables, sequences are user-defined, schema-bound objects that generate a sequence of numeric values. Sequences can be configured to generate values in either ascending or descending order, at a specified interval. Additionally, they can be set to restart (cycle) when the sequence reaches its defined limit, offering more flexibility compared to identity columns.

The change to using SEQUENCE in EF7 is generally beneficial, but if you have existing tables with Identity columns, you may want to continue using Identity instead of the default Sequence. To ensure EF7 uses Identity rather than Sequence, you need to explicitly call the `UseIdentity()` method for the identity property in the `OnModelCreating()` method of your DbContext. This will override the default behavior and configure the column to use an Identity column instead of a Sequence.

For example:

public class TestDbContext : DbContext
{     
    protected override void OnConfiguring(EntityOptionsBuilder optionsBuilder)
    {       
        optionsBuilder.UseSqlServer(connectionString);
    }
 
    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; }
    ....
}

In the example code, the Customer entity has an `Id` property marked with the `[DatabaseGenerated(DatabaseGeneratedOption.Identity)]` attribute, indicating that the `Id` column is an identity column in the database. To ensure EF7 uses an Identity column instead of a Sequence for the `Id` property, you need to call `.ForSqlServer().UseIdentity()` in the `OnModelCreating()` method. This explicitly configures EF7 to treat the `Id` column as an identity column for SQL Server.