【发布时间】:2018-04-16 11:23:28
【问题描述】:
假设我有一个名为Surveys (SurveyId, ... , SubmittedDate, LastEditedDate)的表
它充满了数据,我现在意识到我应该对其进行规范化以将审计数据放入它自己的表中,所以我创建了一个表SurveyAudits (SurveyAuditId, SubmittedDate, LastEditedDate)
当我创建表时,我想用来自
Surveys的数据填充它。然后我需要向
Surveys(SurveyAuditId) 添加一个外键,以便每个调查链接到它的SurveyAudit。最后,我可以从
Surveys(SubmittedDate, LastEditedDate) 中删除多余的列
我应该在 Up 方法中添加什么来实现这一点?
我怀疑我目前的方法可能不合适,所以如果是这种情况,请引导我走上正确的道路!
代码:
public partial class CreateSurveyAudit : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.CreateTable(
name: "SurveyAudits",
columns: table => new
{
SurveyAuditId = table.Column<int>(type: "int", nullable: false).Annotation("SqlServer:ValueGenerationStrategy",SqlServerValueGenerationStrategy.IdentityColumn),
SubmittedDate = table.Column<DateTime>(type: "datetime2", nullable: false),
LastEditedDate = table.Column<DateTime>(type: "datetime2", nullable: false)
},
//I could get the data into the new table like so, but I would not have the relationship:
migrationBuilder.Sql("INSERT INTO SurveyAudits(SubmittedDate, LastEditedDate)
SELECT SubmittedDate, LastEditedDate FROM Surveys")
//so perhaps I could add the foreign key column first
migrationBuilder.AddColumn<int>(...);
migrationBuilder.CreateIndex(...);
migrationBuilder.AddForeignKey(...);
//then something like...
foreach (var survey in context.Surveys) { //but how do I access context?
survey.Add(new SurveyAudit(
SubmittedDate = survey.SubmittedDate,
LastEditedDate = survey.LastEditedDate)
}
context.SaveChanges();
}
}
【问题讨论】:
标签: sql-server entity-framework entity-framework-6 entity-framework-migrations ef-core-2.0