索引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 APIFluent API

Fluent API 可用于根据单个属性中指定的索引。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 API 用于在一组已定义了索引,不论是通过约定或以前配置的属性上配置索引然后你将会更改该索引定义。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.