Skip to content

Instantly share code, notes, and snippets.

@icavalheiro
Created May 24, 2020 15:41
Show Gist options
  • Select an option

  • Save icavalheiro/aaab30bde8adb3ec18309d7bd1c63d49 to your computer and use it in GitHub Desktop.

Select an option

Save icavalheiro/aaab30bde8adb3ec18309d7bd1c63d49 to your computer and use it in GitHub Desktop.
Program.cs example for ASP.NET core 3 that includes database seeding
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using CampaignPortal.Database;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
namespace CampaignPortal
{
public class Program
{
private static void HandleDatabaseCommands(List<string> arguments, IHost host)
{
//we always delete the database, but first lets make sure that the developer knows that
if (!arguments.Contains("--force-db-deletion"))
{
var answer = "";
while (answer.ToLower() != "y" && answer.ToLower() != "n")
{
Console.WriteLine("This will ERASE the database. Are you sure you want to continue? (y/n)");
answer = Console.ReadLine();
}
if (answer == "n")
{
return;
}
}
using (var scope = host.Services.CreateScope())
{
var database = scope.ServiceProvider.GetRequiredService<DatabaseContext>();
database.Database.EnsureDeleted();
Console.WriteLine("Deleted Database");
database.Database.EnsureCreated();
Console.WriteLine("Created Database");
if (arguments.Contains("seed"))
{
Console.WriteLine("Starting seeding...");
Seeds.InstallDeveloperSeeds(database);
Console.WriteLine("Done seeding");
}
}
}
public static void Main(string[] args)
{
var arguments = new List<string>(args);
var host = CreateHostBuilder(args).Build();
if(arguments.Contains("seed") || arguments.Contains("clear"))
{
HandleDatabaseCommands(arguments, host);
}
else
{
Console.WriteLine("Starting server...");
host.Run();
}
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment