Entity Framework - 索引

索引是基于表和视图的磁盘上数据结构.在大多数情况下,索引可以更快,更有效地检索数据.但是,使用索引重载表或视图可能会令其不愉快地影响其他操作(如插入或更新)的性能.

  • 索引是实体框架中的新功能,您可以通过减少从数据库查询数据所需的时间来提高Code First应用程序的性能.

  • 您可以使用索引属性向数据库添加索引,并覆盖默认的唯一群集设置,以获得最适合您的方案的索引.

让我们看看下面的代码,其中在CourseID的Course类中添加了Index属性.

public partial class Course {

   public Course() {
      this.Enrollments = new HashSet<Enrollment>();
   }

   [Index]
   public int CourseID { get; set; }
   public string Title { get; set; }
	
   public int Credits { get; set; }
   public byte[] VersionNo { get; set; }
	
   public virtual ICollection<Enrollment> Enrollments { get; set; }

}

上面创建的密钥是非唯一的,非群集的.有一些重载可用于覆盖这些默认值 :

  • 要使索引成为聚簇索引,您需要指定IsClustered = true

  • 同样,您也可以通过指定IsUnique = true

  • 让我们来看看下面的C#代码,其中索引是聚簇且唯一的.

    public partial class Course {
    
       public Course() {
          this.Enrollments = new HashSet<Enrollment>();
       }
    
       [Index(IsClustered = true, IsUnique = true)]
       public int CourseID { get; set; }
       public string Title { get; set; }
    	
       public int Credits { get; set; }
       public byte[] VersionNo { get; set; }
    	
       public virtual ICollection<Enrollment> Enrollments { get; set; }
    }
  • 索引属性可用于在数据库中创建唯一索引.但是,这并不意味着EF在处理关系等时能够推断列的唯一性.此功能通常被称为对"唯一约束"的支持.