Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can we run SQL script using code first migrations?

Can we run sql script using code first migrations?

I am new to code first and if I want to save my changes to a SQL script file before update-database command of migration, is it possible?

If possible then please provide steps to get it done. Also if script is generated then is it possible that I can run that script using migration?

like image 968
Manprit Singh Avatar asked Aug 20 '15 18:08

Manprit Singh


People also ask

What is the purpose of code first migrations?

Code First Migrations allow you to create a new database or update an existing database based on your model classes using the Package Manager Console for running commands. If you are using the EF code first approach then there are more ways to initialize the database provided by the Entity Framework as follows.


1 Answers

First you need to create a migration.

Add-Migration RunSqlScript 

Then in the generated migration file you can write your SQL.

// PLAIN SQL Sql("UPDATE dbo.Table SET Created = GETDATE()");  // FROM FILE var sqlFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"Custom.sql");  Sql(File.ReadAllText(sqlFile)); 

Then you run

Update-Database 
like image 70
Rikard Avatar answered Sep 27 '22 20:09

Rikard