Skip to content

Execute SQL scripts on ASP.NET Core app startup to seed database.

Notifications You must be signed in to change notification settings

prajwalsharma/dotnetcore-seed-database-startup

Repository files navigation

Execute SQL scripts on App Startup

  1. Implement IHostedService interface
public class HostedService : IHostedService
    {
        public async Task StartAsync(CancellationToken cancellationToken)
        {
            var path = Path.Combine(Directory.GetCurrentDirectory(), "usp_get_users.sql");
            string sql = File.ReadAllText(path);
            using var connection = new SqlConnection("Server=localhost\\SQLEXPRESS;Database=mydb;Trusted_Connection=True;");

            foreach (var item in sql.Split("GO"))
            {
                await connection.ExecuteAsync(item);
            }

        }

        public Task StopAsync(CancellationToken cancellationToken)
        {
            Console.WriteLine("App Stopped!");
            return Task.CompletedTask;
        }
    }
  1. Register it in Program.cs
builder.Services.AddHostedService<HostedService>();

About

Execute SQL scripts on ASP.NET Core app startup to seed database.

Topics

Resources

Stars

Watchers

Forks