dasheddot
dasheddot

Reputation: 2966

Custom code execution in EF migrations

Working with the Entity Frameworks migrations successfully in our project. But now I run into a special case where I need to update a table in need of some business logic (located in our application as C# code). So I tried to spawn a thread in the migrations Up method and doing this table update with the business logic. This table update is not required for the application execution and should be occur in the background.

I am doing this somewhat like this:

public partial class MyMigration : DbMigration
{
  public override void Up()
  {
     // ... do some sql migration here ...

     // after executing the sql migrations custommethod should run
     // migration seems to wait until CustomMethod finished work
     new Thread(() => ExecuteCustomMethodDatabaseContext()).Start();
  }
}

I would expect that the Up method returns after starting the thread and EF sets the migration in the MigrationHistory to done. Thus the app can start and somewhere in the background the table gets updated.

But not so, the migrations seems to run while the thread runs (this takes a LOT of time).

So my according questions:

  1. Is it good practise in general to execute custom code in DBmigrations?
  2. If not, how can I accomplish the need of custom code execution in my case? (without rewriting the business logic in a stored procedure or somewhat)
  3. If yes, what I am doing wrong? How can I execute this code within an migration and without blocking it?

Upvotes: 8

Views: 4865

Answers (1)

bricelam
bricelam

Reputation: 30365

The Up and Down methods on DbMigration merely build up an in-memory model that later gets translated to SQL. You have two options for executing custom logic:

  1. Perform your logic on the database server using T-SQL by using the Sql method.
  2. Perform logic in the Seed method of your migrations configuration class (typically Migrations\Configuration.cs). This gets called after all of the migrations have been applied during Update-Database

Upvotes: 3

Related Questions