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:
- Create a custom value generator for v7 guids.
- Create a custom convention that uses the custom generator
- 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
版权声明:本文标题:c# - How to use guid v7 in EF Core? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1738678729a2106420.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论