I'm using ASP.NET Core and Entity Framework Core. I need to create some views and functions programmatically on the app first start. Is there a way to run some custom SQL code while EF is being configurated?
3 Answers
If you are using code first with entity, you can try execute your sql scripts in migration:
First you need to create a migration:
Add-Migration RunMySqlScripts
Then in the generated migration file you can write your SQL:
// PLAIN SQL
Sql("Your sql code here");
// OR FROM FILE
var sqlFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"scripts.sql");
Sql(File.ReadAllText(sqlFile));
Then you run:
Update-Database
This will be executed only once.
1 Comment
Slip
Thank you! It work with some little changes:
var sqlFile = Path.Combine(AppContext.BaseDirectory,"up.sql"); migrationBuilder.Sql(File.ReadAllText(sqlFile));I use this class for myself. That will run the code only once after the database was initialized.
public class MyDataInitializer
{
public async Task InitializeDatabaseAsync(IServiceProvider serviceProvider)
{
var db = serviceProvider.GetService<MyCustomDB>();
var databaseCreated = await db.Database.EnsureCreatedAsync();
if (databaseCreated)
{
await GenerateData(db);
}
}
private static async Task GenerateData(MyCustomDB context)
{
context.Users.Add(new User
{
Name = "admin",
PasswordParam = "pwd",
});
await context.SaveChangesAsync();
// or execute custom sql here
}
}
And at the end of Startup.Configure(IApplicationBuilder app, ...)
MyDataInitializer dataInitializer = new MyDataInitializer();
await dataInitializer.InitializeDatabaseAsync(app.ApplicationServices);