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?
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).
I found the several answers for this question.
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With