索引Indexes

注意

本節中的組態一般適用於關聯式資料庫。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).

關聯式資料庫中的索引會對應至相同的概念為 Entity framework core 中的索引。An index in a relational database maps to the same concept as an index in the core of Entity Framework.

慣例Conventions

依照慣例,索引會命名為IX_<type name>_<property name>By convention, indexes are named IX_<type name>_<property name>. 對於複合索引<property name>會變成屬性名稱的底線分隔清單。For composite indexes <property name> becomes an underscore separated list of property names.

資料註釋Data Annotations

索引不可以使用資料註解來設定。Indexes can not be configured using Data Annotations.

Fluent APIFluent API

您可以使用 Fluent API 來設定索引的名稱。You can use the Fluent API to configure the name of an index.

class MyContext : DbContext
{
    public DbSet<Blog> Blogs { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Blog>()
            .HasIndex(b => b.Url)
            .HasName("Index_Url");
    }
}

public class Blog
{
    public int BlogId { get; set; }
    public string Url { get; set; }
}

您也可以指定篩選條件。You can also specify a filter.

class MyContext : DbContext
{
    public DbSet<Blog> Blogs { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Blog>()
            .HasIndex(b => b.Url)
            .HasFilter("[Url] IS NOT NULL");
    }
}

public class Blog
{
    public int BlogId { get; set; }
    public string Url { get; set; }
}

當使用 SQL Server 提供者 EF 加上 ' IS NOT NULL' 篩選所有可為 null 的資料行,則唯一索引的一部分。When using the SQL Server provider EF adds a 'IS NOT NULL' filter for all nullable columns that are part of a unique index. 若要覆寫此慣例,您可以提供null值。To override this convention you can supply a null value.

class MyContext : DbContext
{
    public DbSet<Blog> Blogs { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Blog>()
            .HasIndex(b => b.Url)
            .IsUnique()
            .HasFilter(null);
    }
}

public class Blog
{
    public int BlogId { get; set; }
    public string Url { get; set; }
}