admin管理员组

文章数量:1206202

I have updated to .NET 9 and EF Core 9.

I want to replace all Guid.NewGuid() in my database's ID columns with the v7 that shipped with .NET 9: Guid.CreateVersion7().

EF Core does not seem to provide an out-of-the-box way to do this, so I implemented a custom solution.

However, I can't seem to find a way to do it on EF Core out of the box.

The solution I came up with works, but I'm not sure if it is the best one (or even a good one).

This is what I did:

  1. Create a custom value generator for v7 guids.
  2. Create a custom convention that uses the custom generator
  3. Register that convention globally with EF Core

Step 1:

public class GuidV7ValueGenerator : ValueGenerator<Guid>
{
    public override bool GeneratesTemporaryValues => false;
    public override Guid Next(EntityEntry _) => Guid.CreateVersion7();
}

Step 2:

public class GuidV7Convention : IModelFinalizingConvention
{
    public void ProcessModelFinalizing(IConventionModelBuilder modelBuilder, IConventionContext<IConventionModelBuilder> _)
    {
        foreach (var entityType in modelBuilder.Metadata.GetEntityTypes())
        {
            foreach (var property in entityType.GetProperties())
            {
                if (property.ClrType == typeof(Guid) && property.ValueGenerated == ValueGenerated.OnAdd)
                {
                    property.SetValueGeneratorFactory((_, _) => new GuidV7ValueGenerator());
                }
            }
        }
    }
}

Step 3:

public class MyDbContext(...) : DbContext
{
    public DbSet<Foo> Foos { get; set; } = null!;

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        // ...
    }

    protected override void ConfigureConventions(ModelConfigurationBuilder configurationBuilder)
    {
        base.ConfigureConventions(configurationBuilder);
        configurationBuilder.Conventions.Add(_ => new GuidV7Convention());
    }
}

This works.

All my entities have v7 guids now, but is this the way?

本文标签: cHow to use guid v7 in EF CoreStack Overflow