Andrew Duffy
Andrew Duffy

Reputation: 563

How to configure an Identity column using Entity Framework Core?

How do I create an Auto increment identity column in Entity Framework Core?

Obviously I can do it using fluent API for EF6 for example.

Upvotes: 49

Views: 86974

Answers (6)

MB_18
MB_18

Reputation: 2239

Use [DatabaseGenerated(DatabaseGeneratedOption.Identity)] attribute in your model.

For example:

public class Blog
{
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public int BlogId { get; set; }

    public string Url { get; set; }
    public DateTime LastUpdated { get; set; }
}

Upvotes: 5

Greg Z.
Greg Z.

Reputation: 1566

Looks like they changed it once again and the new method now is:

.UseIdentityColumn()

Upvotes: 26

codevision
codevision

Reputation: 5520

With latest bits EF Core 1.0 and up you should use

builder.Entity<ApplicationUser>().Property<int>(nameof(ApplicationUser.AccountNo))
            .UseSqlServerIdentityColumn()

Upvotes: 11

vityanya
vityanya

Reputation: 1176

In latest version of EF7 there is a new extension method to set identity column

protected override void OnModelCreating(ModelBuilder modelBuilder)
{    
  modelBuilder.Entity<MyEntity>(b =>
  {
    b.HasKey(e => e.Identifier);
    b.Property(e => e.Identifier).ValueGeneratedOnAdd();
  });
}

Upvotes: 61

Erik Funkenbusch
Erik Funkenbusch

Reputation: 93424

Since there is very little EF7 documentation, much of what we know we have to glean from the source or unit tests. According to the following two unit tests in the EF7 source...

Here and Here

You would configure a property for Identity like this:

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

And you would configure a property for Sequences like this:

ForSqlServer().UseSequence();

The urls have changed due to the aspnet-core reorg, and the methods have also changed since this was first asked.

Here and Here

if (_useSequence) 
{
    b.Property(e => e.Identifier).ForSqlServerUseSequenceHiLo();
} 
else 
{
    b.Property(e => e.Identifier).UseSqlServerIdentityColumn();
}

It's possible these urls might change again (which is why I include the relevant code), but it's ridiculously easy to just look at the url and go to the site and figure out what the new url is.

Really, the whole point of my answer is that you can figure this stuff out yourself just by going and looking at the unit tests in the source code on GitHub. You shouldn't need someone to spoon feed it to you.

EDIT: Updated links to version 2.1 (still works for 1.1 and 2.0 as well)

Upvotes: 26

Andrew Duffy
Andrew Duffy

Reputation: 563

Here is how to do it explicitly in the event that you want to OR it's not the default behaviour.

protected override void OnModelCreating(ModelBuilder modelBuilder)
{    
  modelBuilder.Entity<MyEntity>(b =>
  {
    b.Key(e => e.Identifier);
    b.Property(e => e.Identifier).ForSqlServer().UseIdentity();
  }
}

Upvotes: 6

Related Questions