Quantcast
Channel: ASP.NET Core
Viewing all articles
Browse latest Browse all 9386

Core 2.1 code-first migrations -- seeding?

$
0
0

Can anyone provide basic code for how to seed a db in dot net core 2.1 ?  In 2.0, I handled this in Program.cs using a scoped instance of my context class:

public class Program
    {
        public static void Main(string[] args)
        {
            var host = BuildWebHost(args);

            using (var scope = host.Services.CreateScope())
            {
                var services = scope.ServiceProvider;

                try
                {
                    var context = services.GetRequiredService<AppDbContext>();
                    DbInitializer.Initialize(context); // seeder
                }
                catch (Exception ex)
                {
                    var logger = services.GetRequiredService<ILogger<Program>>();
                    logger.LogError(ex, "An error occurred while seeding the DB.");
                }
            }

            host.Run();
        }

        public static IWebHost BuildWebHost(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>()
                .Build();
    }

but this doesn't seem to work in 2.1.  When I update the code to use IWebHostBuilder CreateWebHostBuilder (2.1) instead of BuildWebHost, I get an error about WebHostBuilder only allowing creation of a single instance of WebHost.  Here's the updated code I'm trying to work with:

public class Program
    {
        public static void Main(string[] args)
        {
            var host = CreateWebHostBuilder(args);

            using (var scope = host.Start().Services.CreateScope())
            {
                var services = scope.ServiceProvider;

                try
                {
                    var context = services.GetRequiredService<AppDbContext>();
                    DbInitializer.Initialize(context);
                }
                catch (Exception ex)
                {
                    var logger = services.GetRequiredService<ILogger<Program>>();
                    logger.LogError(ex, "An error occurred while seeding the DB.");
                }

                host.Build().Run();
            }
        }

        public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
            WebHost.CreateDefaultBuilder(args)
                .UseStartup<Startup>();
    }

So what's the proper way to seed in 2.1 ? thanks


Viewing all articles
Browse latest Browse all 9386

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>