使用modelbuilder.HasKey在实体框架新迁移中导致错误

问题描述

我有一些实体使用复合键作为主键。 我使用fluentApi配置了它们以设置复合密钥,例如:

modelBuilder.Entity<EntityWithCompositeKey>().HasKey(entity => new { entity.Property1,entity.Property2});

但是在添加新的迁移后要升级数据库时出现错误

system.invalidOperationException: To change the IDENTITY property of a column,the column needs to be dropped and recreated.

经过一番挖掘后,我意识到是由于fluentApi中的这些设置来设置复合键,我认为实体框架想要更改实体的主键以设置新的复合键,但我得到了这个错误...我是对的???我哪里出错了?

由于该错误,我无法更新数据库,并且每次我需要删除迁移文件夹和数据库并重新创建它们时,都可以进行新的更改,并且随着我们越来越接近生产环境,它变得非常烦人。

我正在使用Entity Framework 5rc1和Asp.Net Core 3.1

解决方法

更新列的主键时,需要在迁移记录中删除方法migrationBuilder.AlterColumn,而不删除迁移文件。 这是初始记录。

enter image description here

然后,我添加一个实体并重新迁移。通过migrationBuilder.AlterColumn方法删除Up

enter image description here

数据库中的密钥已更改。

enter image description here