Skip to content Skip to sidebar Skip to footer

Switching To Artificial Key With Different Type In Entity Framework Migrations

I'm working on an Entity Framework Code First project where, previously, I had a class with a field called 'Id' that was a string type and using the hash. That's specified like thi

Solution 1:

Well, I was a little bit hesitant to post the solution I ended up going with, because it feels like a bit of a hack, but since I don't really expect any other answers at this point, here it is.

I ended up hand-editing the migration with this method. Essentially, I'm dropping the constraints, doing an update query to get an nvarchar representation of the integer key, then converting to an int and adding the constraints again.

publicoverridevoidUp()
  {
    DropIndex("dbo.ValueSetElements", new[] { "Parent_Id" });
    DropIndex("dbo.SectionElements", new[] { "Choices_Id" });
    DropForeignKey("dbo.ValueSetElements", "Parent_Id", "dbo.ValueSets");
    DropForeignKey("dbo.SectionElements", "Choices_Id", "dbo.ValueSets");
    DropPrimaryKey(ValueSetTable, "PK_dbo.ValueSets");
    RenameColumn(ValueSetTable, "Id", "Hash");
    AddColumn(ValueSetTable, "Id", c => c.Int(nullable: false, identity: true, name: "Id"));
    AddPrimaryKey(ValueSetTable, "Id");
    CreateIndex(ValueSetTable, "Hash");
    Sql("UPDATE dbo.SectionElements SET Choices_Id = CONVERT(nvarchar(10), (SELECT Id FROM dbo.ValueSets WHERE dbo.ValueSets.Hash = dbo.SectionElements.Choices_Id))");
    AlterColumn("dbo.SectionElements", "Choices_Id", c => c.Int());
    AddForeignKey("dbo.SectionElements", "Choices_Id", "dbo.ValueSets", "Id");
    CreateIndex("dbo.SectionElements", "Choices_Id");
    Sql("ALTER TABLE dbo.ValueSetElements DROP CONSTRAINT [DF__ValueSetE__Paren__0F63164F]");
    Sql("UPDATE dbo.ValueSetElements SET Parent_Id = CONVERT(nvarchar(10), (SELECT Id FROM dbo.ValueSets WHERE dbo.ValueSets.Hash = dbo.ValueSetElements.Parent_Id))");
    AlterColumn("dbo.ValueSetElements", "Parent_Id", c => c.Int(nullable: false));
    AddForeignKey("dbo.ValueSetElements", "Parent_Id", ValueSetTable, "Id", cascadeDelete: true);
    CreateIndex("dbo.ValueSetElements", "Parent_Id");
  }

Post a Comment for "Switching To Artificial Key With Different Type In Entity Framework Migrations"