Skip to main content

EFCore替换ID生成器

使用雪花ID:https://gitee.com/yitter/idgenerator

using SeleniumUtil
/// <summary>
/// 定义自己的ID生成器
/// </summary>
internal class CIDGenerator : ValueGenerator<long>
{
public IIdGenerator Generator { get; set; }
public CIDGenerator(IConfiguration configuration)
{
var generatorId = configuration.GetValue<ushort>("IdGeneratorId");
IdGeneratorOptions options = new IdGeneratorOptions(generatorId);
Generator = new DefaultIdGenerator(options);
}
public override bool GeneratesTemporaryValues { get; }

public override long Next(EntityEntry entry)
{
return Generator.NewLong();
}
}

FluentAPI 处使用 HasValueGenerator 方法替换默认生成

using SeleniumUtil
/// <summary>
/// FluentAPI 处使用 HasValueGenerator 替换
/// </summary>
/// <param name="builder"></param>
protected override void OnModelCreating(ModelBuilder builder)
{
builder.Entity<Todo>(b =>
{
b.ToTable("t_todo");
b.Property(p => p.Id)
.HasColumnName("id")
.HasComment("主键")
.HasValueGenerator<CIDGenerator>()
.ValueGeneratedOnAdd();
b.Property(p => p.Content)
.HasMaxLength(255)
.HasColumnName("content")
.HasComment("内容");
});
}