Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run migration SQL script using Entity Framework Core

Tags:

I faced with an issue, where I can't reach the SQL script to apply the migration. Here is my migration code:

 public partial class AddSomethingMigration : Migration {     private const string MIGRATION_SQL_SCRIPT_FILE_NAME = @"Migrations\Scripts\20170710123314_AddSomethingMigration.sql";      protected override void Up(MigrationBuilder migrationBuilder)     {         string sql = Path.Combine(Directory.GetParent(Directory.GetCurrentDirectory()).FullName, MIGRATION_SQL_SCRIPT_FILE_NAME));         migrationBuilder.Sql(File.ReadAllText(sql));     } } 

So when I use the Package Manager Console on the local machine all works fine. But when I deploy to the environment I get the discrepancy to the file.

Can I run my static SQL scripts via EF migration automatically at all, or I should paste the SQL query inline in code?

like image 455
shkapo Avatar asked Jul 11 '17 13:07

shkapo


People also ask

How do I run a migration in Entity Framework?

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

I found the several answers for this question.

  1. Add scripts as project resources and use it like:

    string sql = Resources._20170630085940_AddMigration; migrationBuilder.Sql(sql); 

This option not so good, because the .sql will embed in the assembly.

  1. If you use Net Core projects with .csproj structure, you can add the itemgroup to xml:

    <ItemGroup> <Content Include="Migrations\**\*.sql" CopyToPublishDirectory="PreserveNewest" /><!-- CopyToPublishDirectory = { Always, PreserveNewest, Never } --></ItemGroup> 

And then specify the path to file like:

Path.Combine(AppContext.BaseDirectory, relativePath) 
like image 90
shkapo Avatar answered Oct 18 '22 22:10

shkapo