Entity Framework 使用 newsequentialid() 作为 Guid Key

Entity Framework uses newsequentialid() for Guid Key

使用下面的代码,

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

    // more properties here
}

我以为 EF 使用的是 newguid(),但是当我检查数据库时,我看到默认值是 newsequentialid()

这是 EF 的默认行为吗?还是因为我使用的是 SQL Server 2017?

你是对的,默认情况下 newsequentialid() 用作 GUID 属性的默认值。 newsequentialid()newid() 更推荐,主要是出于性能方面的考虑。

如果您想将 newid() 作为默认值,您可以通过启用迁移并在 CreateTable() 中指定 defaultValueSql 来实现:

CreateTable(
    "dbo.UserProfiles",
    c => new
        {
            Id = c.Guid(nullable: false, identity: true, defaultValueSql: "newid()"),
            Name = c.String(),
        })
    .PrimaryKey(t => t.Id);