efcore
efcore copied to clipboard
SqlServerPropertyBuilderExtensions.UseSqlServerSequenceHiLo creates sequence with increment 10 instead of 1
Autocreated sequence has increment 10 instead of 1. I've created class User
public class User
{
public long Id { get; set; }
[Required]
[MaxLength(50)]
public string Login { get; set; }
}
and set up dbcontext for it
public class SecurityContext : DbContext
{
public SecurityContext(DbContextOptions options)
: base(options)
{
}
public DbSet<User> Users { get; set; }
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<User>().Property(u => u.Id).UseSqlServerSequenceHiLo("secUser");
base.OnModelCreating(modelBuilder);
}
}
Now I try to add user:
static void Main(string[] args)
{
var b=new DbContextOptionsBuilder();
b.UseSqlServer("server=(local);database=TestEf7;integrated security=true;MultipleActiveResultSets=true;");
var ctx = new SecurityContext(b.Options);
ctx.Database.EnsureCreated();
var user = new User {Login = "user1"};
ctx.Users.Add(user);
ctx.SaveChanges();
}
When I run program 1st time new user will have Id==1. When I run program 2nd time new user will have Id==11. Here sequence scripted from SSMS:
CREATE SEQUENCE [dbo].[secUser]
AS [bigint]
START WITH 1
INCREMENT BY 10
MINVALUE -9223372036854775808
MAXVALUE 9223372036854775807
CACHE
This is by design. The idea is that the EF essentially gets a block of IDs from the database and then uses them to insert until it runs out. So if you change your test code to insert more than one entity before the program exits, then you should see more IDs from the block used.