使用Fluent API在OnModelCreating中配置索引更灵活,支持唯一索引、复合索引和过滤索引;2. 可用[Index]数据注解简化单字段索引定义;3. 支持自定义索引名称和排序;4. 需通过迁移命令生成并应用索引到数据库。

在C#中使用EF Core配置和创建索引,主要是通过Fluent API在OnModelCreating方法中定义,也可以使用数据注解。索引能提升查询性能,尤其在频繁用于WHERE、JOIN或ORDER BY的字段上。
1. 使用Fluent API配置索引
推荐方式是在DbContext的OnModelCreating方法中使用Fluent API来配置索引,这种方式更灵活且功能完整。
示例:
protected override void OnModelCreating(ModelBuilder modelBuilder)
{
// 为User表的Email字段创建唯一索引
modelBuilder.Entity()
.HasIndex(u => u.Email)
.IsUnique();
// 为多个字段创建复合索引
modelBuilder.Entity()
.HasIndex(o => new { o.Status, o.CreatedDate });
// 创建带过滤条件的索引(仅支持SQL Server等部分数据库)
modelBuilder.Entity()
.HasIndex(p => p.CategoryId)
.HasFilter("[IsDeleted] = 0");
}
2. 使用数据注解创建索引
如果不想在OnModelCreating中写配置,可以使用[Index]特性直接标注在实体类的属性上。
示例:
public class User
{
public int Id { get; set; }
[Index(IsUnique = true)]
public string Email { get; set; }
[Index] // 普通索引
public string UserName { get; set; }
}
注意:一个类上不能有多个同名索引,若需复合索引,仍建议使用Fluent API。
3. 索引命名与排序
你可以自定义索引名称,并指定字段排序方式。
modelBuilder.Entity()
.HasIndex(p => p.PublishDate)
.HasDatabaseName("IX_Post_PublishDate_Desc")
.Descending();
4. 应用迁移生成数据库索引
配置完成后,需要通过EF Core迁移将索引应用到数据库。
- 运行命令添加迁移:dotnet ef migrations add AddIndexes
- 更新数据库:dotnet ef database update
执行后,数据库表会自动创建对应索引。
基本上就这些。使用Fluent API更推荐,控制力更强。索引能显著提升查询效率,但也会增加写入开销,应根据实际查询场景合理添加。










