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