【发布时间】:2021-06-22 16:10:00
【问题描述】:
我正在尝试通过迁移来管理复杂的数据模型更改,但我不确定这是不是最好的方法。
在本例中,我有一个 Customer 实体,它具有以下属性:
public string Address { get; set; }
public string PostalOrZip { get; set; }
public string ProvinceOrState { get; set; }
现在,我想创建一个名为 CustomerAddress 的新实体,它拥有相同的 3 个属性,但允许模型为 Customer 保存多个地址
我已经这样做并创建了如下迁移
public partial class customeraddress_table : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "CustomerAddress",
columns: table => new
{
Id = table.Column<int>(type: "int", nullable: false)
.Annotation("SqlServer:Identity", "1, 1"),
CustomerId = table.Column<int>(type: "int", nullable: false),
Address = table.Column<string>(type: "nvarchar(max)", nullable: true),
PostalOrZip = table.Column<string>(type: "nvarchar(max)", nullable: true),
ProvinceOrState = table.Column<string>(type: "nvarchar(max)", nullable: true),
CreatedOn = table.Column<DateTime>(type: "datetime2", nullable: false),
ModifiedOn = table.Column<DateTime>(type: "datetime2", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_CustomerAddress", x => x.Id);
table.ForeignKey(
name: "FK_CustomerAddress_Customer_CustomerId",
column: x => x.CustomerId,
principalTable: "Customer",
principalColumn: "Id",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateIndex(
name: "IX_CustomerAddress_CustomerId",
table: "CustomerAddress",
column: "CustomerId");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "CustomerAddress");
}
}
我想在迁移中做的是遍历所有Customers 并为每个CustomerAddress 创建一个CustomerAddress,并从Customer 复制地址信息。
我一直坚持使用 migrationBuilder.Sql,但使用上下文会很棒,因为我在 SaveChangesAsync 中有有用的逻辑,我需要在 SQL 中复制这些逻辑。
迁移可以处理这样的要求吗?那么有没有比迁移更好的方法呢?
【问题讨论】:
-
您可以做的是在生成的代码之后添加您自己的自定义代码,甚至更好地生成一个新的空白迁移文件,并在 UP 方法中指定
migrationBuilder.Sql(@"wrtie SQL here to move data..."),您将在其中进行您喜欢的数据操作
标签: c# .net-core entity-framework-core asp.net-core-5.0