實體框架 - 索引



索引是基於表和檢視的磁碟上資料結構。在大多數情況下,索引可以使資料檢索更快、更高效。但是,在表或檢視上載入過多的索引可能會對其他操作(如插入或更新)的效能產生負面影響。

  • 索引是實體框架中的新功能,您可以透過減少查詢資料庫所需的時間來提高 Code First 應用程式的效能。

  • 您可以使用Index 屬性向資料庫新增索引,並覆蓋預設的UniqueClustered 設定以獲得最適合您方案的索引。

讓我們看看以下程式碼,其中在 Course 類中為 CourseID 添加了 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; }
}

Index 屬性可用於在資料庫中建立唯一索引。但是,這並不意味著 EF 在處理關係等時能夠推斷出該列的唯一性。此功能通常稱為對“唯一約束”的支援。

廣告

© . All rights reserved.