Entity framework executes SQL before migration

I am working on an existing project that uses Entity-Framework 6 with code one. I need to run some SQL before starting the migration.

I have a DbMigrationsConfiguration class with a seed method, but the seed starts after migration.

I think this will work if I run my SQL in the constructor, but I cannot get the context link.

Does anyone know how to do this?

+8
ef-code-first entity-framework-6
source share
1 answer

You can use the "Sql" method within the desired migration class.

public partial class OneOfYourMigrations : DbMigration { public override void Up() { //EF generated migration code here such as //CreateTable or AddColumn etc... //Now run your custom sql - here I'm doing an update to an existing column Sql("UPDATE dbo.YourTable SET Column1 = 'VALUE1' "); } public override void Down() { //EF generated code to rollback } } 

So the steps are:

  • Generate a migration class using Add-Migration
  • Modify the class using code similar to above
  • Starting migration using Update-Database
+15
source share

All Articles