为什么默认的 newsequentialid() 不起作用?

Why is default newsequentialid() not working?

我有一个 table,默认 idnewsequentialid,但生成的值不是连续的。

[Id] UNIQUEIDENTIFIER DEFAULT (newsequentialid()) NOT NULL
5f3ed690-5110-46c9-2ea8-08d68135eb22
73709d10-81b8-4fcd-2ea9-08d68135eb22
c2320a90-8cd9-4fc7-2eaa-08d68135eb22
a8b2a5a1-0e61-4562-2eab-08d68135eb22
fed58540-42d6-4644-2eac-08d68135eb22
de292204-c00c-49d1-2ead-08d68135eb22
59fe8541-9829-4fa1-2eae-08d68135eb22
90007035-5247-44a9-2eaf-08d68135eb22
dcdbc8dd-a409-435f-2eb0-08d68135eb22
3feba54b-9236-4dfe-2eb5-08d68135eb22

我正在这样填充行:

if (!dbContext.MyTable.Any())
{
    for (int i = 0; i < 100; i++)
    {
        dbContext.MyTable.Add(new MyModel {  Col1= "test", Col2= "test", Created = DateTime.UtcNow });
    }

    await dbContext.SaveChangesAsync();
}

使用 SQL Server Express 2017 14.0.2002

它们在我看来是连续的:

CREATE TABLE guids
(
    id int IDENTITY(1,1) PRIMARY KEY,
    guid uniqueidentifier DEFAULT (newsequentialid()) NOT NULL UNIQUE
)

DECLARE @i int = 0
WHILE @i < 10
BEGIN
    INSERT INTO guids DEFAULT VALUES
    SET @i = @i + 1
END

SELECT *
FROM guids
ORDER BY guid

输出:

+----+--------------------------------------+
| id |                 guid                 |
+----+--------------------------------------+
|  1 | C46ABC87-151F-E911-8566-00155D08A60F |
|  2 | C56ABC87-151F-E911-8566-00155D08A60F |
|  3 | C66ABC87-151F-E911-8566-00155D08A60F |
|  4 | C76ABC87-151F-E911-8566-00155D08A60F |
|  5 | C86ABC87-151F-E911-8566-00155D08A60F |
|  6 | C96ABC87-151F-E911-8566-00155D08A60F |
|  7 | CA6ABC87-151F-E911-8566-00155D08A60F |
|  8 | CB6ABC87-151F-E911-8566-00155D08A60F |
|  9 | CC6ABC87-151F-E911-8566-00155D08A60F |
| 10 | CD6ABC87-151F-E911-8566-00155D08A60F |
+----+--------------------------------------+

请注意,字符串表示的第一个字节是顺序的:C4、C5、C6、C7,...

我发现我需要将以下内容添加到 ApplicationDbContext

中的 OnModelCreating 方法中
modelBuilder.Entity<MyModel>().Property(x=>x.Id).HasDefaultValueSql("NEWSEQUENTIALID()");