【发布时间】:2017-01-14 00:55:14
【问题描述】:
在我的数据库中,我有两个表;人和别名。最初,People 包含一系列字段,包括FirstName、MiddleName 和LastName。别名还包含 FirstName、MiddleName 和 LastName,但行与 People 中的一行相关联,一个独特的人。
我更改了模型,使 People 不再包含 FirstName、MiddleName 和 LastName,并将字段 IsPrimary 添加到 Alias。
我创建了一个迁移文件,它应该反映这些表的新状态。我现在要做的是添加到迁移文件代码中,该代码将获取 People 表中的每一行,获取 FirstName、MiddleName 和 LastName 字段中的数据,在 Alias 中创建一个新行,插入FirstName、MiddleName 和 LastName 进入该新行,并将 IsPrimary 字段设置为 true。这将在 Up 方法中。我需要为 down 功能做相反的事情。
如何在迁移文件中执行这些操作?
这是迁移文件的一部分:
using System;
using System.Collections.Generic;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Metadata;
namespace ACC.Data.Migrations
{
public partial class Add_IsPrimary_To_Alias : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "People",
columns: table => new
{
Id = table.Column<Guid>(nullable: false),
DOB = table.Column<DateTime>(nullable: true),
EyeColor = table.Column<string>(nullable: true),
Facility = table.Column<string>(nullable: true),
HairColor = table.Column<string>(nullable: true),
HeightInches = table.Column<int>(nullable: false),
Notes = table.Column<string>(nullable: true),
PrimaryPhone = table.Column<string>(nullable: true),
Race = table.Column<string>(nullable: true),
Sex = table.Column<string>(nullable: true),
WeightLbs = table.Column<int>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_People", x => x.Id);
});
migrationBuilder.CreateTable(
name: "Aliases",
columns: table => new
{
Id = table.Column<Guid>(nullable: false),
FirstName = table.Column<string>(nullable: true),
IsPrimary = table.Column<bool>(nullable: false),
LastName = table.Column<string>(nullable: true),
MiddleName = table.Column<string>(nullable: true),
PersonId = table.Column<Guid>(nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_Aliases", x => x.Id);
table.ForeignKey(
name: "FK_Aliases_People_PersonId",
column: x => x.PersonId,
principalTable: "People",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "Aliases");
migrationBuilder.DropTable(
name: "People");
}
}
}
在环顾四周后,我找到了一些关于 Data Motion and Custom SQL 的文档。
目前还没有对数据移动的原生支持...
这是否意味着我想要实现的目标是不可能的?
谢谢!
【问题讨论】:
-
可以显示当前的迁移文件吗?
-
@Sampath 我已经编辑了问题。
标签: c# sql-server database entity-framework database-migration