Jacob C
Jacob C

Reputation: 81

Entity Framework Code First Migrations Guid NewId Instead Of NewSequentialId

We're using EF6 with code first migrations pointing to an Azure SQL. We've started into using some Guid for both primary keys as well as alongside int primary keys.
Primary Key:

[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Id { get; set; }

Alongside int PK:

[Index, DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid PolymorphicId { get; set; }

When I generate the migration, I get as follows (respectively):

Id = c.Guid(nullable: false, identity: true),
PolymorphicId = c.Guid(nullable: false, identity: true),

Expectation: SQL generated to have default values of newsequentialid

Actually Happening:

[Id] [uniqueidentifier] NOT NULL DEFAULT newid(),
[PolymorphicId] [uniqueidentifier] NOT NULL DEFAULT newid(),

How do I make my EF migrations generate with newsequentialid instead of newid? Everything I've looked up online says that they should be generating with newsequentialid.

Upvotes: 3

Views: 1165

Answers (2)

Jacob C
Jacob C

Reputation: 81

When targeting Azure, SqlServerMigrationSqlGenerator will default to "newid()". When targeting on-premesis Sql Server 2005 or later, it will default to "newsequentialid()". Source: GitHub SqlServerMigrationSqlGenerator.cs

Optional fix: Create a custom SqlGenerator, inheriting SqlServerMigrationSqlGenerator, override GuidColumnDefault

Optional fix: As posted by JFM, modify the generated migration file, setting the defaultValueSql

Upvotes: 2

JFM
JFM

Reputation: 753

You could try setting the sql used by the sql server column key generation in your migration script, I beleive it should look somethnig similar to this:

Id = c.Guid(nullable: false, identity: true, defaultValueSql: "newsequentialid()")

Upvotes: 0

Related Questions