简体   繁体   English

如何在 EF Core 3.1 中重命名 PrimaryKey 和 ForeignKey?

[英]How to rename PrimaryKey and ForeignKey in EF Core 3.1?

I recently rename the column name on my DB.我最近重命名了我的数据库上的列名。 When create a new migration and what I see: EF Core immediately drop column and create a new one.当创建一个新的迁移和我看到的:EF Core 立即删除列并创建一个新的列。 It doesn't make sense to me.这对我来说没有意义。 Is there any rename foreign key or primary key method?是否有任何重命名外键或主键方法?

Use " HasConstraintName " fluent API like this :像这样使用“ HasConstraintName ”流畅的 API:

protected override void OnModelCreating(ModelBuilder modelBuilder)
{
    modelBuilder.Entity<Student>()
        .HasMany(c => c.Employees)
        .WithOne(e => e.Company)
        .HasConstraintName("NamFKConstraint");
}

MigrationsModelDiffer is the service class that detects model changes. MigrationsModelDiffer是检测模型更改的服务类。 It "works" by comparing two snapshots of your database model to guess what you changed.它通过比较您的数据库模型的两个快照来猜测您更改了什么来“工作”。 Column renames will probably only be detected if nothing else about the column was changed.重命名可能只有在列没有其他任何更改时才会被检测到。 If you make too many changes at once, then the missing columns will be dropped and new ones added.如果您一次进行太多更改,则会删除丢失的列并添加新列。

If this isn't what you want, you'll need to modify the migration script to specify column renames & other type changes by hand.如果这不是您想要的,您需要修改迁移脚本以手动指定列重命名和其他类型更改。

            migrationBuilder.RenameColumn(
                name: "old_name",
                table: "table_name",
                newName: "new_name");

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM