Skip to content

Instantly share code, notes, and snippets.

@unaizorrilla
Created September 12, 2017 14:30
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save unaizorrilla/17ee153933ef253a22b6a7f6a744e423 to your computer and use it in GitHub Desktop.
Save unaizorrilla/17ee153933ef253a22b6a7f6a744e423 to your computer and use it in GitHub Desktop.
EF Core DotNet tool Migrations and Seed
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using System;
using System.Linq;
namespace EFSeedDemo
{
public class Program
{
public static void Main(string[] args)
{
BuildWebHost(args)
.MigrateDbContext<SomeDbContext>(context =>
{
if (!context.SomeEntities.Any())
{
context.SomeEntities.Add(new SomeEntity());
context.SaveChanges();
}
}).Run();
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.Build();
}
}
namespace Microsoft.AspNetCore.Hosting
{
public static class IWebHostExtensions
{
public static IWebHost MigrateDbContext<TContext>(this IWebHost webHost,Action<TContext> seeder) where TContext : DbContext
{
using (var scope = webHost.Services.CreateScope())
{
var context = scope.ServiceProvider.GetService<TContext>();
try
{
context.Database
.Migrate();
seeder(context);
}
catch (Exception ex)
{
var logger = scope.ServiceProvider.GetRequiredService<ILogger<TContext>>();
logger.LogError(ex, "An error occurred while migrating the database.");
}
}
return webHost;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment