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.
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.
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