Created
September 12, 2017 14:30
-
-
Save unaizorrilla/17ee153933ef253a22b6a7f6a744e423 to your computer and use it in GitHub Desktop.
EF Core DotNet tool Migrations and Seed
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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