I want to add a new column with a unique index to an existing table using a code first migration. Because the table already has data, all existing rows are set to NULL for the new column when it's created. The migration fails to apply because this violates the unique constraint of the new index.
Here is my migration:
public override void Up()
{
AddColumn("dbo.SignInToken", "Token", c => c.String(maxLength: 32));
// How can I update existing rows here?
CreateIndex("dbo.SignInToken", "Token", unique: true);
}
And the error:
The CREATE UNIQUE INDEX statement terminated because a duplicate key was found for the object name 'dbo.SignInToken' and the index name 'IX_Token'. The duplicate key value is ().
The new column will contain a randomly generated string which I set in code.
I know that I can use the Sql method to execute raw SQL within the migration. I thought of using a cursor to update each row, but then I would have to write a stored procedure to mimic the C# method which generates the random token. I would prefer not to have to do this. Another thing I thought of was that if there were a way to retrieve all of the rows, I could loop through them and execute the update statements on each row using the Sql method, but I don't know if this is possible.
Is there a way to update all existing rows individually from within the migration before adding the unique constraint?