Sergi0
Sergi0

Reputation: 1096

ASP EF7 Set column value in migration

I want to move from autoincrement ids to composite primary keys. So, these two entities

public class SeasonTeam
{
    public int SeasonTeamId { get; set; }
    public int SeasonId { get; set; }   
    public int TeamId { get; set; }
}


public class GroupEntry
{
    public int GroupEntryId { get; set; }
    public int SeasonTeamId { get; set; }

    public SeasonTeam SeasonTeam { get; set; }
}

will now look like this

public class SeasonTeam
{
    public int SeasonId { get; set; }   
    public int TeamId { get; set; }
}


public class GroupEntry
{
    public int GroupEntryId { get; set; }
    public int SeasonId { get; set; }   
    public int TeamId { get; set; }

    public SeasonTeam SeasonTeam { get; set; }
}

Visual Studio generated migration code, but it corrupts data.

migrationBuilder.AddColumn<int>(
    name: "SeasonId",
    table: "GroupEntry",
    nullable: false,
    defaultValue: 0);

migrationBuilder.AddColumn<int>(
    name: "TeamId",
    table: "GroupEntry",
    nullable: false,
    defaultValue: 0);



migrationBuilder.DropForeignKey(name: "FK_GroupEntry_SeasonTeam_SeasonTeamId", table: "GroupEntry");
migrationBuilder.DropPrimaryKey(name: "PK_SeasonTeam", table: "SeasonTeam");
migrationBuilder.DropColumn(name: "SeasonTeamId", table: "SeasonTeam");

Default value 0 obviously won't work, I need ids from referenced SeasonTeam table, but I didn't find any examples. How can I set proper id values for a new composite key before I delete old primary key column?

Upvotes: 1

Views: 1052

Answers (1)

natemcmaster
natemcmaster

Reputation: 26823

You can't do this programmatically with EF's APIs, however, if you can write the SQL to move the values from one table to another, you can add a custom migration step after the Add column operations and before the drop column operations.

migrationBuilder.Sql(@"INSERT INTO ...(your SQL here)");

From the limited info in your question, I can't tell you what that SQL should be.

Upvotes: 1

Related Questions