在.Net项目的EFCore的Code First 模式中如何实现默认部分字段添加索引
具体实现可参考NetCoreKevin
一个基于NET8搭建DDD-微服务-现代化Saas企业级WebAPI前后端分离架构:前端Vue3、IDS4单点登录、多级缓存、自动任务、分布式、AI智能体、一库多租户、日志、授权和鉴权、CAP事件、SignalR、领域事件、MCP协议服务、IOC模块化注入、Cors、Quartz自动任务、多短信、AI、AgentFramework、SemanticKernel集成、RAG检索增强+Qdrant矢量数据库、OCR识别、API多版本、单元测试、RabbitMQ
项目地址:github:https://github.com/junkai-li/NetCoreKevin
使用 HasIndex 方法指定字段
在实体类配置中通过 HasIndex 方法直接指定需要添加索引的字段。例如为 Name 和 Email 字段添加索引:
modelBuilder.Entity<User>()
.HasIndex(u => new { u.Name, u.Email });
配置默认索引命名规则
通过 modelBuilder 的配置统一设置索引命名规则,避免手动命名。例如使用以下方式配置:
modelBuilder.Entity<User>()
.HasIndex(u => u.Name)
.HasDatabaseName("IX_Default_Name");
使用 Fluent API 批量添加索引
在 OnModelCreating 方法中通过循环或反射批量为特定字段添加索引。例如为所有字符串类型的属性添加索引:
foreach (var entity in modelBuilder.Model.GetEntityTypes())
{
foreach (var property in entity.GetProperties())
{
if (property.ClrType == typeof(string))
{
entity.AddIndex(property);
}
}
}
通过数据注解标记索引字段
直接在实体类的属性上使用 [Index] 注解标记需要索引的字段。例如:
public class User
{
[Index]
public string Name { get; set; }
}
配置复合索引
为多个字段创建复合索引时,指定字段顺序和排序方式。例如:
modelBuilder.Entity<User>()
.HasIndex(u => new { u.LastName, u.FirstName })
.IsDescending(false, true);
使用 Include 属性包含非键字段
在索引中包含非键字段以提高查询性能。例如:
modelBuilder.Entity<User>()
.HasIndex(u => u.Id)
.IncludeProperties(u => u.Name);
设置索引的筛选条件
为索引添加筛选条件以优化特定查询场景。例如为活跃用户添加筛选索引:
modelBuilder.Entity<User>()
.HasIndex(u => u.Name)
.HasFilter("[IsActive] = 1");

浙公网安备 33010602011771号