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.
CodePudding user response:
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.
CodePudding user response:
You could try doing something like this(It's meant to be DbContext).Emloyees(or however your table is called).FromSqlRaw. Or look better here: https://www.learnentityframeworkcore.com/raw-sql