我有以下模型:
public class Promotion : BaseModel
{
[Required]
public string Description { get; set; }
[Required]
public string Market { get; set; }
[Required]
public double Price { get; set; }
}
已创建一个已迁移到数据库的迁移。并且在数据库中插入了一些 promotions 。但是我需要将促销模型更改为:
public class Promotion : BaseModel
{
[Required]
public string Description { get; set; }
[Required]
public Market Market { get; set; }
[Required]
public double Price { get; set; }
}
public class Market : BaseModel
{
[Required]
public string Name { get; set; }
[Required]
public string Adress { get; set; }
}
当我添加新的迁移时,我得到了警报:“操作脚手架可能会导致数据丢失。请检查迁移的准确性。”
这是新迁移自动生成的Up方法:
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropColumn(
name: "Market",
table: "Promotions");
migrationBuilder.AddColumn<Guid>(
name: "MarketId",
table: "Promotions",
nullable: false,
defaultValue: new Guid("00000000-0000-0000-0000-000000000000"));
migrationBuilder.CreateTable(
name: "Markets",
columns: table => new
{
Id = table.Column<Guid>(nullable: false),
Adress = table.Column<string>(nullable: false),
CreatedAt = table.Column<DateTime>(nullable: false),
DeletedAt = table.Column<DateTime>(nullable: false),
Name = table.Column<string>(nullable: false),
UpdatedAt = table.Column<DateTime>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Markets", x => x.Id);
});
migrationBuilder.CreateIndex(
name: "IX_Promotions_MarketId",
table: "Promotions",
column: "MarketId");
migrationBuilder.AddForeignKey(
name: "FK_Promotions_Markets_MarketId",
table: "Promotions",
column: "MarketId",
principalTable: "Markets",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
}
如何在不丢失数据的情况下更新数据库?
答案 0 :(得分:6)
升级生产数据库的安全方法是将其分解为多个步骤:
Market
实体并将其附加到Promotion
实体without dropping the existing column
CREATE TABLE
+ ADD FOREIGN KEY
语句Market table
到Market column
和Market table
来更新/插入/选择新值Market column
复制到Market table
。运行。现在,您已将数据移至新的Market table
,并且新数据位于Market table
Market column
。部署变更Market column
。 EF将在列将被删除的位置生成迁移。部署这个。现在,您已经迁移了数据和架构