Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

.NET 6 - Entity Framework Core migrations seed from SQL scripts

I have a .NET Core application with Entity Framework migrations. I am seeding the database in OnModelCreating(), like this:

modelBuilder.Entity<Employee>().HasData(
    new Employee { Id = 1, Name = "Peter", idDepartment = 3 },
    new Employee { Id = 2, Name = "Rose", idDepartment = 5 },
    ...
);

But for some tables, I have SQL scripts that I want to run instead.

How can I run these scripts in OnModelCreating()? The SQL scripts are stored in some .sql files.

like image 946
patsy2k Avatar asked Dec 11 '25 08:12

patsy2k


1 Answers

You can create custom empty migration and copypaste your scripts queries directly into that migration. With new C# 11 raw string literals feature it would be quite simply (literaly copy and paste) to do.

Something like that:

public partial class PureSqlMigration : Migration
{
    /// <inheritdoc />
    protected override void Up(MigrationBuilder migrationBuilder)
    {
        var sql =
            $"""
            update dbo.Folders set FullPath = 'Creating Digital Images - EDIT' where FolderId = 1
        """;
        migrationBuilder.Sql(sql);
    }

    /// <inheritdoc />
    protected override void Down(MigrationBuilder migrationBuilder)
    {
        
    }
}

Then run it. Don't forget about rollback actions if you need them. Hope it will help.

like image 108
Ryan Avatar answered Dec 12 '25 20:12

Ryan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!