How to run SQL script migration using Entity Framework core

I am facing an issue where I am unable to contact 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 my local machine everything works fine. But when I deploy the environment, I get a file mismatch.

Can I run my static SQL scripts via EF migrations automatically at all, or should I insert an inline SQL query into the code?

Any help would be appreciated. Thank.

+3


source to share


1 answer


I have found several answers to this question.

  • Add scripts as project resources and use them like:

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

This option is not very good because the .sql will be inserted into the assembly.



  1. If you are using Net Core projects with .csproj construct, you can add the item group to the xml:

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

And then provide the path to the file, for example:

Path.Combine(AppContext.BaseDirectory, relativePath)

      

+5


source







All Articles