Невозможно запустить миграцию для .Net Core перед развертыванием на героку - PullRequest
0 голосов
/ 14 июня 2019

У меня есть API ядра dotnet, размещенный на heroku с использованием docker для моего развертывания, после подключения базы данных postgresql к приложению, которое я решил, что мне нужно запустить миграцию, поэтому я добавил эту часть в свой файл .csproj

<Target Name="PrePublishTarget" AfterTargets="Publish">
  <Exec Command="dotnet ef database update" />
</Target>

Вот мой запуск

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }
    readonly string mySpecificOrigin = "VotingBlockOrigin";

    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddScoped<IUnitOfWork, UnitOfWork>();
        services.AddScoped<IUserRepository, UserRepository>();
        services.AddScoped<IElectionRepository, ElectionRepository>();
        services.AddSingleton<IConfiguration>(Configuration);
        var appSettingsSection = Configuration.GetSection("AppSettings");
        services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        services.AddAutoMapper();
        services.Configure<AppSettings>(Configuration.GetSection("AppSettings"));
        services.AddDbContext<VotingDBContext>(options =>{

            var env = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
            string connStr;
            if (env == "Development") {
                connStr = Configuration.GetConnectionString("DefaultConnection");
            } else {
               var connUrl = Environment.GetEnvironmentVariable("HEROKU_POSTGRESQL_SILVER_URL");
                connUrl = connUrl.Replace("postgres://", string.Empty);

                var pgUserPass = connUrl.Split("@")[0];
                var pgHostPortDb = connUrl.Split("@")[1];
                var pgHostPort = pgHostPortDb.Split("/")[0];

                var pgDb = pgHostPortDb.Split("/")[1];
                var pgUser = pgUserPass.Split(":")[0];
                var pgPass = pgUserPass.Split(":")[1];
                var pgHost = pgHostPort.Split(":")[0];
                var pgPort = pgHostPort.Split(":")[1];

                connStr = $"Server={pgHost};Port={pgPort};User Id={pgUser};Password={pgPass};Database={pgDb};sslmode=Prefer;Trust Server Certificate=true";
                Console.WriteLine("ConnectionString: " + connStr);
            }
        options.UseNpgsql(connStr);
        });
        var appSettings = appSettingsSection.Get<AppSettings>();
        var key = Encoding.ASCII.GetBytes(appSettings.Secret);
        services.AddAuthentication(auth => {
           auth.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme;
           auth.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme;
        })
        .AddJwtBearer(x => {
           x.RequireHttpsMetadata = false;
           x.SaveToken = true;
           x.TokenValidationParameters = new TokenValidationParameters
           {
               ValidateIssuerSigningKey = true,
               IssuerSigningKey = new SymmetricSecurityKey(key),
               ValidateIssuer = false,
               ValidateAudience = false
           };
        });
    }
   public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }
        else
        {
            app.UseHsts();
        }
         app.UseCors(x => x.AllowAnyHeader().AllowAnyMethod().AllowAnyOrigin().AllowCredentials());
        app.UseHttpsRedirection();
        app.UseMvc();
        app.UseDefaultFiles();
        app.UseStaticFiles();
        app.UseAuthentication();
    }
}

Вот ошибка

Microsoft.EntityFrameworkCore.Infrastructure [10403] Entity Framework Core 2.1.11-servicing-32099 инициализировал VotingDBContext с помощьюпоставщик Npgsql.EntityFrameworkCore.PostgreSQL с параметрами: Нет
System.Net.Internals.SocketExceptionFactory + ExtendedSocketException (99): невозможно назначить запрошенный адрес [:: 1]: 5432

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...