在 EF6.2上 ,您可以
HasIndex()用来添加索引以通过fluent API进行迁移。
https://github.com/aspnet/Entityframework6/issues/274
例
modelBuilder .Entity<User>() .HasIndex(u => u.Email) .IsUnique();
从 EF6.1 开始,您可以使用
IndexAnnotation()fluent API添加用于迁移的索引。
http://msdn.microsoft.com/zh-
cn/data/jj591617.aspx#PropertyIndex
您必须添加对以下内容的引用:
using System.Data.Entity.Infrastructure.Annotations;
基本范例
这是一个简单的用法,在
User.FirstName属性上添加索引
modelBuilder .Entity<User>() .Property(t => t.FirstName) .HasColumnAnnotation(IndexAnnotation.AnnotationName, new IndexAnnotation(new IndexAttribute()));
实际示例:
这是一个更现实的例子。它将在多个属性上添加 唯一索引 :
User.FirstName和
User.LastName,索引名称为“
IX_FirstNameLastName”
modelBuilder .Entity<User>() .Property(t => t.FirstName) .IsRequired() .HasMaxLength(60) .HasColumnAnnotation( IndexAnnotation.AnnotationName, new IndexAnnotation( new IndexAttribute("IX_FirstNameLastName", 1) { IsUnique = true }));modelBuilder .Entity<User>() .Property(t => t.LastName) .IsRequired() .HasMaxLength(60) .HasColumnAnnotation( IndexAnnotation.AnnotationName, new IndexAnnotation( new IndexAttribute("IX_FirstNameLastName", 2) { IsUnique = true }));


