ASP EF7 Set column value in migration

asp.net-core asp.net-core-mvc ef-migrations entity-framework-core

Question

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?

1
1
2/24/2016 5:28:30 PM

Accepted Answer

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.

1
3/1/2016 12:27:06 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow