Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?
like image 349
dasheddot Avatar asked Nov 14 '12 07:11

dasheddot


People also ask

How do I run EF migrations?

Open the Package Manager Console from Tools → Library Package Manager → Package Manager Console and then run the enable-migrations command (make sure that the default project is the project where your context class is).


1 Answers

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
like image 97
bricelam Avatar answered Sep 25 '22 10:09

bricelam