PAYATHON 2026

EF Core 一对多关系却生成 ApplicationUserId 唯一索引怎么办

数据小陈

结论

EF Core 默认给一对多关系的外键建非唯一索引,单靠 HasOne<ApplicationUser>().WithMany() 不会生成唯一索引。若 IX_RefreshTokens_ApplicationUserId 是唯一约束,通常是下面几种情况:模型把这段关系识别成了一对一;存在显式或遗留的唯一索引配置;迁移快照或数据库里已经保留了唯一索引。HasIndex(...).IsUnique(false) 改的是索引元数据,无法覆盖一对一关系本身对唯一性的要求。只要关系元数据里的 IsUnique 为 true,迁移仍会生成唯一索引。

为什么会出现唯一索引

  1. 关系被配成了一对一。如果其他位置写了 HasOne<RefreshToken>().WithOne(),或者误用了 WithOne(),EF Core 会强制在外键上建唯一索引。
  2. 索引配置被合并或覆盖。HasIndex(rt => rt.ApplicationUserId).IsUnique(false) 需要确认最终模型里的索引确实是非唯一。如果关系生成了唯一索引,显式配置未必按预期生效。
  3. 迁移快照或数据库里有残留。EnsureCreatedAsync 按当前模型建库,迁移则按快照生成。迁移里仍是 unique: true,说明模型或快照里还有唯一索引。
  4. 显式唯一约束。之前可能加过 HasIndex(...).IsUnique() 或 HasAlternateKey,后来没有清理。

排查模型元数据

先在运行时检查 ForeignKey 和 Index 的 IsUnique:

var entityType = context.Model.FindEntityType(typeof(RefreshToken))!;

foreach (var fk in entityType.GetForeignKeys())
{
    Console.WriteLine(fk.IsUnique);
}

foreach (var index in entityType.GetIndexes())
{
    Console.WriteLine(index.IsUnique);
}

重点看 ApplicationUserId 对应的 ForeignKey 的 IsUnique 是否为 true。如果是 true,说明关系被当成一对一,应先修正关系。如果 FK 为 false 而 Index 为 true,就检查显式索引和迁移快照。

正确配置一对多关系

保留 WithMany(),不要写成 WithOne():

public class RefreshTokenConfiguration : IEntityTypeConfiguration<RefreshToken>
{
    public void Configure(EntityTypeBuilder<RefreshToken> builder)
    {
        builder.ToTable("RefreshTokens");

        builder.HasKey(rt => rt.Id);

        builder.HasOne<ApplicationUser>()
            .WithMany()
            .HasForeignKey(rt => rt.ApplicationUserId)
            .OnDelete(DeleteBehavior.Restrict);

        builder.HasIndex(rt => rt.ApplicationUserId)
            .IsUnique(false);
    }
}

如果要在 ApplicationUser 上增加集合导航,可以这样写:

public class ApplicationUser : IdentityUser<Guid>
{
    public ICollection<RefreshToken> RefreshTokens { get; set; } = new List<RefreshToken>();
}
builder.HasOne(rt => rt.ApplicationUser)
    .WithMany(u => u.RefreshTokens)
    .HasForeignKey(rt => rt.ApplicationUserId)
    .OnDelete(DeleteBehavior.Restrict);

集合导航不是必需的。关键是别误用 WithOne()。

清理迁移和快照

如果迁移里仍然是这样:

migrationBuilder.CreateIndex(
    name: "IX_RefreshTokens_ApplicationUserId",
    table: "RefreshTokens",
    column: "ApplicationUserId",
    unique: true);

说明模型快照或迁移本身还带着唯一索引。可以删掉旧迁移重新生成,也可以新增迁移显式修改索引:

dotnet ef migrations remove
dotnet ef migrations add FixRefreshTokenIndex
dotnet ef database update

如果数据库里已经有唯一索引,迁移要先删除再创建非唯一索引:

migrationBuilder.DropIndex(
    name: "IX_RefreshTokens_ApplicationUserId",
    table: "RefreshTokens");

migrationBuilder.CreateIndex(
    name: "IX_RefreshTokens_ApplicationUserId",
    table: "RefreshTokens",
    column: "ApplicationUserId",
    unique: false);

如果 PostgreSQL 报的是唯一约束而不是普通索引,应使用 DropConstraint 删除约束,再重建非唯一索引。执行前先确认对象类型,免得迁移失败。

注意事项

  • 一对多外键不需要唯一索引,同一用户可以有多个刷新令牌。
  • 如果业务上确实要求每个用户只能有一个刷新令牌,应使用一对一关系或唯一索引,并在登录时更新或替换旧令牌,而不是继续追加。
  • 使用 EnsureCreatedAsync 时,数据库结构完全由当前模型决定。模型里有唯一索引就一定会创建。生产环境建议统一使用迁移,避免 EnsureCreated 和迁移混用。
  • 检查 OnModelCreating 中 base.OnModelCreating(builder) 之后有没有其他配置覆盖了 RefreshToken 的关系。
  • 修改后先删库或执行迁移,再验证 IX_RefreshTokens_ApplicationUserId 的 unique 属性。

备注:内容仅供参考。