public static void Main(string[] args) { var host = CreateWebHostBuilder(args).Build(); using (var scope = host.Services.CreateScope()) { var services = scope.ServiceProvider; try { var context = services. GetRequiredService <ApplicationContext>(); // Seeding de datos. Seeding.Initialize(services); } catch (Exception ex) { var logger = services.GetRequiredService <ILogger <Program> >(); logger.LogError(ex, "An error occurred seeding the DB."); } } host.Run(); }
// Creates and seeds an ApplicationContext with test data; then calls test action. private async Task PrepareTestContext(TestAction testAction) { // Database is in memory as long the connection is open var connection = new SqliteConnection("DataSource=:memory:"); try { connection.Open(); var options = new DbContextOptionsBuilder <ApplicationContext>() .UseSqlite(connection) .Options; // Create the schema in the database and seeds with test data using (var context = new ApplicationContext(options)) { context.Database.EnsureCreated(); Seeding.Initialize(context); await testAction(context); } } finally { connection.Close(); } }
public static async Task TestSeedDb(IHost host) { using (IServiceScope scope = host.Services.CreateScope()) { var services = scope.ServiceProvider; await Seeding.Initialize(services); } }
protected override void ConfigureWebHost(IWebHostBuilder builder) { builder.ConfigureServices(services => { var dbContextDescriptor = services.Single(d => d.ServiceType == typeof(DbContextOptions <CarManagerContext>)); services.Remove(dbContextDescriptor); services.AddDbContext <CarManagerContext>(options => options.UseInMemoryDatabase(nameof(CarManagerContext))); using var scope = services.BuildServiceProvider().CreateScope(); var scopedProvider = scope.ServiceProvider; var context = scopedProvider.GetRequiredService <CarManagerContext>(); if (context.Database.EnsureCreated()) { Seeding.Initialize(context); } }); }
private static void CreateDbIfNotExists(IHost host) { using (var scope = host.Services.CreateScope()) { var services = scope.ServiceProvider; try { // Seed the Identity-related database if have not done so var UR_context = services.GetRequiredService <UserRoleDB>(); Seeding.Initialize(UR_context); } catch (Exception ex) { var logger = services.GetRequiredService <ILogger <Program> >(); logger.LogError(ex, "An error occurred creating the DB."); } } }