using Microsoft.EntityFrameworkCore.Migrations; #nullable disable namespace AmtScanner.Api.Migrations { /// public partial class AddDeviceWindowsCredentials : Migration { /// protected override void Up(MigrationBuilder migrationBuilder) { // 使用原生 SQL 安全删除外键和索引(如果存在) migrationBuilder.Sql(@" SET @fk_exists = (SELECT COUNT(*) FROM information_schema.TABLE_CONSTRAINTS WHERE CONSTRAINT_SCHEMA = DATABASE() AND TABLE_NAME = 'RemoteAccessTokens' AND CONSTRAINT_NAME = 'FK_RemoteAccessTokens_WindowsCredentials_WindowsCredentialId'); SET @sql = IF(@fk_exists > 0, 'ALTER TABLE RemoteAccessTokens DROP FOREIGN KEY FK_RemoteAccessTokens_WindowsCredentials_WindowsCredentialId', 'SELECT 1'); PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt; "); migrationBuilder.Sql(@" SET @idx_exists = (SELECT COUNT(*) FROM information_schema.STATISTICS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'RemoteAccessTokens' AND INDEX_NAME = 'IX_RemoteAccessTokens_WindowsCredentialId'); SET @sql = IF(@idx_exists > 0, 'ALTER TABLE RemoteAccessTokens DROP INDEX IX_RemoteAccessTokens_WindowsCredentialId', 'SELECT 1'); PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt; "); migrationBuilder.Sql(@" SET @col_exists = (SELECT COUNT(*) FROM information_schema.COLUMNS WHERE TABLE_SCHEMA = DATABASE() AND TABLE_NAME = 'RemoteAccessTokens' AND COLUMN_NAME = 'WindowsCredentialId'); SET @sql = IF(@col_exists > 0, 'ALTER TABLE RemoteAccessTokens DROP COLUMN WindowsCredentialId', 'SELECT 1'); PREPARE stmt FROM @sql; EXECUTE stmt; DEALLOCATE PREPARE stmt; "); migrationBuilder.AddColumn( name: "WindowsPassword", table: "AmtDevices", type: "longtext", nullable: true) .Annotation("MySql:CharSet", "utf8mb4"); migrationBuilder.AddColumn( name: "WindowsUsername", table: "AmtDevices", type: "longtext", nullable: true) .Annotation("MySql:CharSet", "utf8mb4"); } /// protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropColumn( name: "WindowsPassword", table: "AmtDevices"); migrationBuilder.DropColumn( name: "WindowsUsername", table: "AmtDevices"); migrationBuilder.AddColumn( name: "WindowsCredentialId", table: "RemoteAccessTokens", type: "bigint", nullable: true); migrationBuilder.CreateIndex( name: "IX_RemoteAccessTokens_WindowsCredentialId", table: "RemoteAccessTokens", column: "WindowsCredentialId"); migrationBuilder.AddForeignKey( name: "FK_RemoteAccessTokens_WindowsCredentials_WindowsCredentialId", table: "RemoteAccessTokens", column: "WindowsCredentialId", principalTable: "WindowsCredentials", principalColumn: "Id", onDelete: ReferentialAction.SetNull); } } }