How to configure Key Identity column in Entity Framework 7?



I have the following Mapper in Entity Framework 7 RC1:

  b.HasKey(x => x.Id);
  b.Property(x => x.Id) ... ??

How to make Id and identity column in EF 7 RC1?

The SQL equivalent is:

Id int identity not null

I've read that would be like this:

b.Property(x => x.Id).ForSqlServer().UseIdentity();

But in EF7 RC1 I do not find ForSqlServer(). I do find:

12/16/2015 5:05:44 PM

Accepted Answer

You can explicitly configure an identity column by calling.

b.Property(x => x.Id).UseSqlServerIdentityColumn();

Also worth noting: identity is the default value generation pattern used with primary keys. Using sequences is opt-in.

12/17/2015 10:00:34 PM

Popular Answer

The answer provided by natemcmaster is correct. You can define with fluentAPI or you can also use Data Annotation [Key] to define Primary Key.

However there are couple of ways to define identity value in EF Core. You can use identity (default), Sequence and HiLo Pattern with Sequence. Identity is default. In fact you don't have to define it as identity column if your property name ending with Id or <typeName> Id. EF Core by convention configures a property named Id or <typeName>Id as the key of an entity.

And the reason for having extension method name starting from ForSqlServer is that, EF Core supports many database providers. And functionality for these providers are slightly different so you are able to specify a different behavior for the same property depending on the provider being used.

Please read these article to know more about using Sequcence with EF Core and HiLo with EF core.

Related Questions


Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow