我想将ASP.Net core 2.2中模型的主键的数据类型从int更改为long,因为它即将超出int范围。该应用程序先执行代码,然后使用SQL Server作为数据库。
更改模型中的数据类型也可以运行“添加迁移”,但是Update-Database失败,并显示以下错误:
System.Data.SqlClient.SqlException (0x80131904): The index 'IX_tblMTransactions_OriginalTransactionId' is dependent on column 'OriginalTransactionId'.
The object 'FK_tblMTransactions_tblMTransactions_OriginalTransactionId' is dependent on column 'OriginalTransactionId'.
所以我读到它,似乎需要对迁移进行一些调整,例如在更改列之前先删除外键和索引,然后再将它们放回原处。不幸的是,我在.net core 2.2中找不到有关执行此操作的任何有用信息,我找到的最接近的信息是this question,但它谈到了.net core 2.1以及选项DropForeignKey
和{{1} }
提到this article ,. net core 2.2似乎不再可用。
这是迁移类:
DropIndex
有人知道如何在.NET Core 2.2中调整迁移类以使其正常工作吗?
谢谢
答案 0 :(得分:2)
感谢Ivan Stoev,我找到了解决方案。我必须像这样手动添加索引和键的删除和创建:
public partial class _20190817_2317 : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropForeignKey(
name: "FK_tblMTransactions_tblMTransactions_OriginalTransactionId",
table: "tblMTransactions");
migrationBuilder.DropIndex(
name: "IX_tblMTransactions_OriginalTransactionId",
table: "tblMTransactions");
migrationBuilder.DropPrimaryKey(
name: "PK_tblMTransactions",
table: "tblMTransactions");
migrationBuilder.AlterColumn<long>(
name: "OriginalTransactionId",
table: "tblMTransactions",
nullable: true,
oldClrType: typeof(int),
oldNullable: true);
migrationBuilder.AlterColumn<long>(
name: "Id",
table: "tblMTransactions",
nullable: false,
oldClrType: typeof(int))
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn)
.OldAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
migrationBuilder.AddPrimaryKey(
name: "PK_tblMTransactions",
table: "tblMTransactions",
column: "Id");
migrationBuilder.CreateIndex(
name: "IX_tblMTransactions_OriginalTransactionId",
table: "tblMTransactions",
column: "OriginalTransactionId");
migrationBuilder.AddForeignKey(
name: "FK_tblMTransactions_tblMTransactions_OriginalTransactionId",
table: "tblMTransactions",
column: "OriginalTransactionId",
principalTable: "tblMTransactions",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.AlterColumn<int>(
name: "OriginalTransactionId",
table: "tblMTransactions",
nullable: true,
oldClrType: typeof(long),
oldNullable: true);
migrationBuilder.AlterColumn<int>(
name: "Id",
table: "tblMTransactions",
nullable: false,
oldClrType: typeof(long))
.Annotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn)
.OldAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
}
}
再次感谢,伊万!