0

We use Entity Framework. And I have an issue with a table in the DB.

The Id is a GUID where we create a new GUID manually. Now I want to implement a new column to auto increment and I want this to start at 100000000. To make the column auto increment is working ok (I think)

 Company {
    private Guid id = Guid.NewGuid();

    [Required, Range(10000000, 999999999)]
    [Index(IsUnique = true)]
    [DatabaseGenerated(DatabaseGeneratedOption.Identity)]
    public virtual long StakeholderNumber
    {
        get;
        set;
    }
 }

When adding the migration, I get this migrationfile;

    public override void Up()
    {
        AlterColumn("dbo.Companies", "StakeholderNumber", c => c.Long(nullable: false, identity: true));
        CreateIndex("dbo.Companies", "StakeholderNumber", unique: true);
    }

    public override void Down()
    {
        DropIndex("dbo.Companies", new[] { "StakeholderNumber" });
        AlterColumn("dbo.Companies", "StakeholderNumber", c => c.Long(nullable: false));
    }

This looks to work. BUT I want the stakeholderNumber to start at 100000000 instead of 1. From other examples, this could work by setting stakeholdernumber to primary and then add the line:

        Sql("DBCC CHECKIDENT ('dbo.Companies', RESEED, 100000000);");

BUT I do not want stakeholdernumber to be primary!

If I run this with updadte-database, I get this error:

Companies' does not contain an identity column

SO is there a way to set auto increment on Stakeholdernumber to 10000000 without making the column primary?

TorK
  • 567
  • 2
  • 10
  • 27
  • Can you show the complete example - the original entity model/configuration and modified entity/configuration. – Ivan Stoev May 19 '17 at 07:33
  • Actually the issue is that the migration does **not** change the existing column to `IDENTITY`. Take a look at [Migrate entity with updated DatabaseGeneratedOption in Entity-Framework](http://stackoverflow.com/questions/30462749/migrate-entity-with-updated-databasegeneratedoption-in-entity-framework) to get some ideas how to resolve it. – Ivan Stoev May 19 '17 at 08:00
  • what about just setting the default value in SQL to MAX+1, instead of trying to use entity framework to do it. – Gerrie Pretorius Jan 03 '18 at 14:10

1 Answers1

2

I had the same issue and ended using sequence instead. I defined a sequence and then used it like so

protected override void OnModelCreating(ModelBuilder builder)
    {
        base.OnModelCreating(builder);

        builder.HasSequence<int>("MySequence", schema: "shared").StartsAt(10000000).IncrementsBy(1);

         modelBuilder.Entity<Company>()
        .Property(o => o.StakeholderNumber)
        .HasDefaultValueSql("NEXT VALUE FOR shared.MySequence");            
    } 

Works perfect for me. I am using EF core 2.0.
Ref:https://learn.microsoft.com/en-us/ef/core/modeling/relational/sequences

Hope it helps!