序列Sequences

注意

本節中的組態一般適用於關聯式資料庫。The configuration in this section is applicable to relational databases in general. 當您因共用 Microsoft.EntityFrameworkCore.Relational 套件而安裝關聯式資料庫提供者時,這裡顯示的擴充方法會變成可用。The extension methods shown here will become available when you install a relational database provider (due to the shared Microsoft.EntityFrameworkCore.Relational package).

序列會在資料庫中產生連續的數字值。A sequence generates a sequential numeric values in the database. 順序不會與特定資料表相關聯。Sequences are not associated with a specific table.

慣例Conventions

依照慣例,未導入序列中的模型。By convention, sequences are not introduced in to the model.

資料註釋Data Annotations

您可以設定使用資料註解的順序。You can not configure a sequence using Data Annotations.

Fluent APIFluent API

您可以使用 Fluent API 模型中建立的順序。You can use the Fluent API to create a sequence in the model.

class MyContext : DbContext
{
    public DbSet<Order> Orders { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.HasSequence<int>("OrderNumbers");
    }
}

public class Order
{
    public int OrderId { get; set; }
    public int OrderNo { get; set; }
    public string Url { get; set; }
}

您也可以設定的順序,例如結構描述、 開始值和遞增值的其他層面。You can also configure additional aspect of the sequence, such as its schema, start value, and increment.

class MyContext : DbContext
{
    public DbSet<Order> Orders { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.HasSequence<int>("OrderNumbers", schema: "shared")
            .StartsAt(1000)
            .IncrementsBy(5);
    }
}

序列導入之後,您可以使用它來在模型中產生屬性的值。Once a sequence is introduced, you can use it to generate values for properties in your model. 例如,您可以使用預設值插入序列中的 [下一步] 的值。For example, you can use Default Values to insert the next value from the sequence.

class MyContext : DbContext
{
    public DbSet<Order> Orders { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.HasSequence<int>("OrderNumbers", schema: "shared")
            .StartsAt(1000)
            .IncrementsBy(5);

        modelBuilder.Entity<Order>()
            .Property(o => o.OrderNo)
            .HasDefaultValueSql("NEXT VALUE FOR shared.OrderNumbers");
    }
}

public class Order
{
    public int OrderId { get; set; }
    public int OrderNo { get; set; }
    public string Url { get; set; }
}