.NET 9 introduced Guid.CreateVersion7() / Guid.CreateVersion7(DateTimeOffset) methods to create sortable UUIDs / GUIDs based on the time of their creation. This can be particularly useful in databases where you want to maintain a chronological order of records (plus some perf benefits).
Currently, there is no native way to configure Entity Framework to use these methods when generating new GUIDs for primary keys. But we can do this on our own.
Value Generator
First, we need to create a custom value generator that will use Guid.CreateVersion7() to generate new GUIDs.
public class UUIDv7Generator : ValueGenerator<Guid>
{
public override bool GeneratesTemporaryValues => false;
public override Guid Next(EntityEntry entry)
{
// Uses DateTimeOffset.UtcNow internally, so we don't need to pass it explicitly
return Guid.CreateVersion7();
}
}
Use it as:
public class MyDbContext : DbContext
{
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
modelBuilder.Entity<MyEntity>()
.Property(e => e.Id)
.HasValueGenerator<UUIDv7Generator>()
.ValueGeneratedOnAdd();
}
}
Et voilá! Now, whenever a new MyEntity has sortable UUIDs as primary key. If you want that there is a convenient way to apply this generator in Entity Framework, you can upvote the following ticket: https://github.com/dotnet/efcore/issues/34158