Example #1
0
        private async Task Migration_request(bool useCustomPath)
        {
            using (var database = SqlTestStore.CreateScratch())
            {
                var optionsBuilder = new DbContextOptionsBuilder();
                optionsBuilder.UseSqlite(database.ConnectionString);

                var path = useCustomPath ? new PathString("/EndPoints/ApplyMyMigrations") : MigrationsEndPointOptions.DefaultPath;

                using var host = new HostBuilder()
                                 .ConfigureWebHost(webHostBuilder =>
                {
                    webHostBuilder
                    .UseTestServer()
                    .Configure(app =>
                    {
                        if (useCustomPath)
                        {
                            app.UseMigrationsEndPoint(new MigrationsEndPointOptions
                            {
                                Path = path
                            });
                        }
                        else
                        {
                            app.UseMigrationsEndPoint();
                        }
                    })
                    .ConfigureServices(services =>
                    {
                        services.AddDbContext <BloggingContextWithMigrations>(options =>
                        {
                            options.UseSqlite(database.ConnectionString);
                        });
                    });
                }).Build();

                await host.StartAsync();

                var server = host.GetTestServer();

                using (var db = BloggingContextWithMigrations.CreateWithoutExternalServiceProvider(optionsBuilder.Options))
                {
                    var databaseCreator = db.GetService <IRelationalDatabaseCreator>();
                    Assert.False(databaseCreator.Exists());

                    var formData = new FormUrlEncodedContent(new List <KeyValuePair <string, string> >
                    {
                        new KeyValuePair <string, string>("context", typeof(BloggingContextWithMigrations).AssemblyQualifiedName)
                    });

                    HttpResponseMessage response = await server.CreateClient()
                                                   .PostAsync("http://localhost" + path, formData);

                    Assert.Equal(HttpStatusCode.NoContent, response.StatusCode);

                    Assert.True(databaseCreator.Exists());

                    var historyRepository = db.GetService <IHistoryRepository>();
                    var appliedMigrations = historyRepository.GetAppliedMigrations();
                    Assert.Equal(2, appliedMigrations.Count);
                    Assert.Equal("111111111111111_MigrationOne", appliedMigrations.ElementAt(0).MigrationId);
                    Assert.Equal("222222222222222_MigrationTwo", appliedMigrations.ElementAt(1).MigrationId);
                }
            }
        }