索引Indexes

索引是跨多個資料存放區的一般概念。Indexes are a common concept across many data stores. 其資料存放區中的實作可能有所不同,它們用來使資料行 (或一組資料行) 為基礎的查閱更有效率。While their implementation in the data store may vary, they are used to make lookups based on a column (or set of columns) more efficient.

慣例Conventions

依照慣例,會當做外部索引鍵使用每個屬性 (或屬性集) 中建立索引。By convention, an index is created in each property (or set of properties) that are used as a foreign key.

資料註釋Data Annotations

可以使用資料註解建立索引。Indexes can not be created using data annotations.

關於 fluent 應用程式開發介面Fluent API

若要在單一屬性上指定的索引,您可以使用 fluent 應用程式開發的應用程式開發介面。You can use the Fluent API to specify an index on a single property. 根據預設,索引為非唯一的。By default, indexes are non-unique.

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

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

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

您也可以指定索引應該是唯一的這表示任何兩個實體可以有相同的值為指定的屬性。You can also specify that an index should be unique, meaning that no two entities can have the same value(s) for the given property(s).

        modelBuilder.Entity<Blog>()
            .HasIndex(b => b.Url)
            .IsUnique();

您也可以指定多個資料行的索引。You can also specify an index over more than one column.

class MyContext : DbContext
{
    public DbSet<Person> People { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<Person>()
            .HasIndex(p => new { p.FirstName, p.LastName });
    }
}

public class Person
{
    public int PersonId { get; set; }
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

提示

沒有每個相異的屬性集的一個索引。There is only one index per distinct set of properties. 如果您使用 fluent 應用程式開發的應用程式開發介面來設定索引上的一組屬性已索引定義,藉由慣例或先前的設定,然後將會變更該索引的定義。If you use the Fluent API to configure an index on a set of properties that already has an index defined, either by convention or previous configuration, then you will be changing the definition of that index. 這非常有用,如果您想要進一步設定由慣例所建立的索引。This is useful if you want to further configure an index that was created by convention.