【问题标题】:Normalise table in Entity Framework Core and migrate existing data规范化 Entity Framework Core 中的表并迁移现有数据
【发布时间】:2018-04-16 11:23:28
【问题描述】:

假设我有一个名为Surveys (SurveyId, ... , SubmittedDate, LastEditedDate)的表

它充满了数据,我现在意识到我应该对其进行规范化以将审计数据放入它自己的表中,所以我创建了一个表SurveyAudits (SurveyAuditId, SubmittedDate, LastEditedDate)

  1. 当我创建表时,我想用来自Surveys 的数据填充它。

  2. 然后我需要向Surveys (SurveyAuditId) 添加一个外键,以便每个调查链接到它的SurveyAudit

  3. 最后,我可以从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


    【解决方案1】:

    您需要在SurveyAudits 表上创建一个SurveyId 列来建立关系

    然后使用以下内容:

        migrationBuilder.Sql("INSERT INTO SurveyAudits(SurveyId, SubmittedDate, LastEditedDate)
                              SELECT SurveyId, SubmittedDate, LastEditedDate FROM Surveys")
    

    【讨论】:

    • 但是这种关系是错误的。调查有一个 SurveyAudit,因此调查需要有 SurveyAuditId 作为外键,而不是 SurveyAudit 有 SurveyId 作为外键。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-10-27
    • 2022-12-09
    • 2017-05-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多