How should custom code work during the migration of an Entity Framework database?

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?

+4
source share
1 answer

Migration is a change in schema , so you cannot use AddOrUpdate () objects inside the migration. But you can, and this is what I suggest you, run simple SQL code using the Sql() method.

+2
source

Source: https://habr.com/ru/post/1499465/


All Articles