实体框架核心:脚手架,避免更改模型/实体后数据丢失

时间:2018-07-01 21:52:31

标签: asp.net-core entity-framework-core scaffolding

我有以下模型:

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);
    }

如何在不丢失数据的情况下更新数据库?

1 个答案:

答案 0 :(得分:6)

升级生产数据库的安全方法是将其分解为多个步骤:

  1. 添加新的Market实体并将其附加到Promotion实体without dropping the existing column
  2. EF将为您带来迁移-CREATE TABLE + ADD FOREIGN KEY语句
  3. 让您的代码更喜欢从Market tableMarket columnMarket table来更新/插入/选择新值
  4. 您部署它。现在,您既有包含数据的旧列又有新表,它们正在同步新数据。
  5. 写入数据迁移,该迁移会将旧值从Market column复制到Market table。运行。现在,您已将数据移至新的Market table,并且新数据位于Market table
  6. 更新代码以停止使用旧的Market column。部署变更
  7. 从您的实体中删除Market column。 EF将在列将被删除的位置生成迁移。部署这个。现在,您已经迁移了数据和架构