EF Core 7.0.2迁移时莫名重命名并重复生成表问题求助
EF Core 7.0.2 迁移异常问题求助
我在使用EF Core 7.0.2时遇到了异常行为,具体情况如下:
实体类定义
TargetEntity
[Table("target"), Index(nameof(Prefix), IsUnique = true)] internal sealed class TargetEntity { [Key, Column("target_id")] public long Id { get; set; } [Column("name"), MaxLength(64)] public string Name { get; set; } = default!; [Column("description"), MaxLength(256)] public string? Description { get; set; } [Column("prefix")] public char Prefix { get; set; } [Column("group_link_id")] public long? GroupLinkId { get; set; } [ForeignKey(nameof(GroupLinkId))] public GroupEntity GroupLink { get; set; } = default!; }
GroupEntity
[Table("group")] internal sealed class GroupEntity { [Key, Column("group_id")] public long Id { get; set; } [Column("name"), MaxLength(64)] public string Name { get; set; } = default!; [Column("description"), MaxLength(256)] public string? Description { get; set; } [Column("group_link_id")] public long? GroupLinkId { get; set; } [ForeignKey(nameof(GroupLinkId))] public GroupEntity GroupLink { get; set; } = default!; }
DbContext配置
internal DbSet<GroupEntity> GroupEntity { get; set; } = default!; internal DbSet<TargetEntity> TargetEntity { get; set; } = default!;
未自定义OnModelCreating方法。
迁移异常表现
几周前创建了初始迁移,后续两次迁移都正常。但昨天修改代码后生成新迁移时,EF Core无理由生成了表重命名指令:
migrationBuilder.RenameTable( name: "target", newName: "Target"); migrationBuilder.RenameTable( name: "group", newName: "Group");
同时还生成了重复的建表代码,例如group表的重复创建代码:
migrationBuilder.CreateTable( name: "group", columns: table => new { groupid = table.Column<long>(name: "group_id", type: "bigint", nullable: false) .Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn), name = table.Column<string>(type: "character varying(64)", maxLength: 64, nullable: false), description = table.Column<string>(type: "character varying(256)", maxLength: 256, nullable: true), grouplinkid = table.Column<long>(name: "group_link_id", type: "bigint", nullable: true) }, constraints: table => { table.PrimaryKey("PK_group", x => x.groupid); table.ForeignKey( name: "FK_group_group_group_link_id", column: x => x.grouplinkid, principalTable: "group", principalColumn: "group_id"); });
已尝试的解决方法
- 删除所有迁移文件并删除数据库
- 重新创建初始迁移,但EF Core仍会为每个表生成两次建表代码
搜索引擎未找到有效解决方案,恳请提供解决办法。
内容的提问来源于stack exchange,提问作者Pavel Dorokhov
相关产品推荐
相关产品推荐

