序列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 應用程式開發介面Fluent 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. 例如,您可以使用Default Values從序列中插入下一個值。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; }
}