I have a very simple Entity Framework 5 DbMigration that adds a new boolean column to an existing table with thousands of records. I want the initial value of this column for each existing row to be set based on the value in two other columns in the same table. This should only affect existing records, so it should only be done when migrating and never run again.
This is basically the logic that needs to be executed:
var users = (from u in context.Users select u).ToList(); users.ForEach(u => { u.MyNewBoolColumn = (u.Column1 != null && u.Column2 == "some-value"); context.Users.AddOrUpdate(u); });
There are two options that I can think of, but I donβt like any of them:
- Create two separate migrations because the column will not exist until the first one is completed. This seems sloppy, and I'm also not sure how to get the database context in the second migration in order to actually perform the upgrade.
- Run code in the implementation of DbMigrationsConfiguration. However, this code will run every time, and I wonβt know if it has already been run and should not update records.
Is there any other better option?
source share