原文連接:https://www.entityframeworktutorial.net/entityframework6/index-attribute-in-code-first.aspx
javascript
EF 6 Code-First系列文章目錄:html
EF 6提供了Index特性,用來在特定的列上面建立索引。java
class Student
{
public int Student_ID { get; set; }
public string StudentName { get; set; }
[Index]
public int RegistrationNumber { get; set; }
}
默認狀況下,索引的名稱是IX_{屬性的名稱},可是你能夠修改屬性的名稱。
一樣你還能夠經過IsClustered=true
來建立聚合索引,或者經過IsUnique=true
來建立惟一索引。數據庫
[Index( "INDEX_REGNUM", IsClustered=true, IsUnique=true )]
public int RegistrationNumber { get; set; }
理論學習完了,咱們練習一下:
1.建立一個控制檯應用程序,安裝好EF:
2.建立一個Student類:app
public class Student
{
public int StudentID { get; set; }
public string StudentName { get; set; }
/// <summary>
/// 表 'dbo.Students' 中的列 'RowVersion' 的類型不能用做索引中的鍵列。
/// string類型的屬性,不能建立索引
/// </summary>
//[Index]
//public string RowStringVersion { get; set; }
[Index]
public decimal RowDecimalVersion { get; set; }
}
3.建立上下文類:ide
public class EFDbContext:DbContext
{
public EFDbContext() : base("name=Constr") {
}
public DbSet<Student> Students { get; set; }
}
4.SQL鏈接字符串:學習
<!--SQL鏈接字符串-->
<connectionStrings> <add name="Constr" connectionString="Server=.;Database=EFAnnotationIndexDB;uid=sa;pwd=Password_1" providerName="System.Data.SqlClient"/> </connectionStrings>
5.測試代碼:測試
class Program
{
static void Main(string[] args) {
using (var db = new EFDbContext())
{
List<Student> lstModel= db.Students.ToList();
}
Console.WriteLine("success");
Console.ReadKey();
}
}
6.運行程序:
看看生成的數據庫:
ui
能夠看到RowDecimalVersion列生成了一個默認的索引IX_RowDecimalVersion【不惟一,非彙集】
注意:一個表只能有一個彙集索引,而後不能對字符串類型的列,設置索引.spa