gpt4 book ai didi

asp.net-core - Entity Framework 核心 : Scaffolding to Avoid Data Loss after to change Model/Entity

转载 作者:行者123 更新时间:2023-12-03 18:41:10 25 4
gpt4 key购买 nike

我有以下模型:

public class Promotion : BaseModel
{
[Required]
public string Description { get; set; }

[Required]
public string Market { get; set; }

[Required]
public double Price { get; set; }
}

它创建了一个更新到数据库的迁移。并且在数据库中插入了一些促销信息。但是我需要将促销模型更改为:
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);
}

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

最佳答案

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

  • 添加新的 Market 实体并将其附加到 Promotion 实体 without dropping the existing column
  • EF 将为您生成迁移 - CREATE TABLE + ADD FOREIGN KEY 语句
  • 使您的代码从 Market tableMarket column 中更新/插入/选择新值,更喜欢 Market table
  • 你部署这个。现在,您已经获得了包含数据的旧列和新表,并与新数据同步。
  • 编写数据迁移,将旧值从 Market column 复制到 Market table 。运行。现在您已将数据移至新的 Market table 并且新数据位于 Market table
  • 更新您的代码以停止使用旧的 Market column 。部署更改
  • 从您的实体中删除 Market column。 EF 将生成迁移,其中列将被删除。部署这个。您现在已迁移数据和架构
  • 关于asp.net-core - Entity Framework 核心 : Scaffolding to Avoid Data Loss after to change Model/Entity,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51127275/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com