Create table and insert data into it during EF code first migration

A way to do "random" things in migrations is to use the Sql method and pass whatever SQL statement you need to perform, for example, inserting data.

This is the best approach if you want your migrations to be able to generate a complete migration SQL script, including your data operations (the Seed method can only be executed in code and won't generate any sql script).


You can try this approach: after creating table, create another empty migration in your Package Manager Console using:

Add-Migration "MigrationName"

Then open the .cs file of that migration and, in Up() method, insert this code:

Sql("INSERT INTO MyNewTable(NyColumnName) Values('Test')");

After that, save and go back to Package Manager Console and update the database using:

Update-Database

My recommendation is move that insert code to the Seed method. Migrations introduced its own Seed method on the DbMigrationsConfiguration class. This Seed method is different from the database initializer Seed method in two important ways:

  • It runs whenever the Update-Database PowerShell command is executed. Unless the Migrations initializer is being used the Migrations Seed method will not be executed when your application starts.
  • It must handle cases where the database already contains data because Migrations is evolving the database rather than dropping and recreating it.

For that last reason it is useful to use the AddOrUpdate extension method in the Seed method. AddOrUpdate can check whether or not an entity already exists in the database and then either insert a new entity if it doesn’t already exist or update the existing entity if it does exist.

So, try to run the script that you want this way:

 Update-Database –TargetMigration: ScriptName 

And the Seed method will do the job of inserting data.

As Julie Lerman said on her blog:

The job of AddOrUpdate is to ensure that you don’t create duplicates when you seed data during development.


For those who looking for EF Core solution, In the Up method, and after creating the table:

i.e: migrationBuilder.CreateTable(name: "MyTable", .....

add the following code:

migrationBuilder.InsertData(table: "MyTable", column: "MyColumn", value: "MyValue");

or

migrationBuilder.InsertData(table: "MyTable", columns: ..., values: ...);

For more information see the docs: MigrationBuilder.InsertData Method