NewSequentialID() 是 SQL Server 中的一个内置函数,用于生成连续的 GUID 值。在实体框架(Entity Framework)中,当需要将 GUID 作为主键时,可以使用这个函数来自动生成值。
public class MyEntity
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Id { get; set; }
// 其他属性...
}
然后在迁移中指定默认值:
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "MyEntities",
columns: table => new
{
Id = table.Column<Guid>(nullable: false, defaultValueSql: "NEWSEQUENTIALID()"),
// 其他列...
},
constraints: table =>
{
table.PrimaryKey("PK_MyEntities", x => x.Id);
});
}
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public Guid Id { get; set; }
然后在 SQL Server 中设置列的默认值为 NEWSEQUENTIALID()。
如果不需要使用 SQL Server 特定功能,可以考虑:
在大量插入场景下,使用 NewSequentialID() 通常比随机 GUID 有显著性能提升,特别是在表有聚集索引的情况下。测试表明插入性能可提高 2-5 倍,索引碎片化减少 70% 以上。