Home > database >  How to run SQL scripts in .NET 6 using EF Core Code first migration
How to run SQL scripts in .NET 6 using EF Core Code first migration

Time:01-31

I have below folder structure for each migration in my class library project. How would I get a proper file path with name and run it in Up method of migration file. enter image description here

For every migration I am using folders as 1,2 and so on.

CodePudding user response:

Use FluentMigrator package and write migration class like this:

public class YourMigration : Migration
{
    public override void Up()
    {
        Execute.Script($"{AppDomain.CurrentDomain.BaseDirectory}/path_to_your_script/your_script.sql");
    }

    public override void Down()
    {
    }
}

CodePudding user response:

I would reccomend giving your files different filenames. Then You can add your text files to a resources (.resx) file.

Creating a resources file in Visual Studio:

  • Right click the folder where you want to add the resources file
  • Hover over "Add"
  • Click "New Item"
  • Search for "resources file" in the search bar
  • Select "resources file" and create one with your desired name

You add resources (other files in this case) to the resource (.resx) file by, double clicking it, pressing Add Resource (make sure Files is selected in the dropdown to the left of "Add Resource") then finding and opening the desired file using the explorer window that pops up.

enter image description here

Then, if you are using EF Core, you can run SQL from your text files by adding the following to your migration:

protected override void Up(MigrationBuilder migrationBuilder)
{
    migrationBuilder.Sql(YourResourcesFile.YourTextFile);
}

Note: you must replace "YourResourcesFile" with your resource file name and "YourTextFile" with your text file name.

  • Related