【问题标题】:EntityFrameworkCore Key column auto increment from specific valueEntityFrameworkCore Key 列从特定值自动递增
【发布时间】:2019-05-07 21:28:12
【问题描述】:

具有自动递增的Key 列的简单类

public class SomeClass
{
    [Key]
    public long SomeClassId { get; set;}
}

通常SomeClassId 会从 1 开始并自动递增。是否有强制 ID 从特定数字开始,比如 10001?

建议here通过Sql()执行CHECKIDENT命令。但是我想知道是否还有其他方法可以解决这个问题?

谢谢!

【问题讨论】:

  • @demo 这就是我在问题中提到的方法,使用CHECKIDENT。我在问我们是否可以通过其他方式实现。此外,那篇文章是针对 EF6 的,我问的是 EF Core 2.2

标签: c# entity-framework-core ef-core-2.2


【解决方案1】:

是的,您可以使用 Fluent API .示例代码

class MyContext : DbContext
{
    public DbSet<SomeClass> sample{ get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.HasSequence<int>("sampleNumber", schema: "shared")
            .StartsAt(10001)
            .IncrementsBy(1);  
        modelBuilder.Entity<SomeClass>()
        .Property(o => o.SomeClassId)
        .HasDefaultValueSql("NEXT VALUE FOR shared.sampleNumber");
    }
    }

【讨论】:

猜你喜欢
  • 2021-09-02
  • 1970-01-01
  • 1970-01-01
  • 2011-03-29
  • 2023-03-30
  • 2021-10-31
  • 2016-11-15
  • 2016-03-07
  • 1970-01-01
相关资源
最近更新 更多