ConnectionString NULL - PullRequest
       56

ConnectionString NULL

0 голосов
/ 06 апреля 2019

Я получаю эту ошибку:

Произошло необработанное исключение при обработке запроса.ArgumentNullException: значение не может быть нулевым.Имя параметра: connectionString

Мой DbContext:

public class ApplicationDBContext : DbContext
{
    public ApplicationDBContext(DbContextOptions<ApplicationDBContext> options) : base(options)
    {
    }

    public DbSet<AcumuladoStock> AcumuladoStockDB { get; set; }
    public DbSet<CabeceraPedidoCliente> CabeceraPedidoClienteDB { get; set; }

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);
    }

    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
    {
        base.OnConfiguring(optionsBuilder);
        var builder = new ConfigurationBuilder()
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
        IConfigurationRoot config = builder.Build();

        optionsBuilder.UseSqlServer(config.GetConnectionString("DefaultConnection"));
    }
}

public class AcumuladoStock
{
        [Key]
        public int CodigoEmpresa { get; set; }

        public string Ejercicio { get; set; }
        public string CodigoArticulo { get; set; }
        public string Periodo { get; set; }
        public string Partida { get; set; }
        public string UnidadSaldo { get; set; }
}

Мой запуск:

public void ConfigureServices(IServiceCollection services)
{
    // services.AddTransient<GetAcumuladoController>();
    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
    services.AddDbContext<ApplicationDBContext>(options => 
        options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))
    );
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    var builder = new ConfigurationBuilder()
       .SetBasePath(env.ContentRootPath)
       .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
       .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);

    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }
    else
    {
        app.UseHsts();
    }

    app.UseHttpsRedirection();
    app.UseMvc();
}

Appsettings.json:

{ 
  "ConnectionString": { 
    "DefaultConnection": "Server=XXXXX; Database=XXX; User Id=xx; Password=XXXXX; Pooling=true;" 
  }, 
  "Logging": { 
    "LogLevel": { 
      "Default": "Warning" 
    } 
  }, 
  "AllowedHosts": "*" 
} 

1 Ответ

1 голос
/ 06 апреля 2019

ConfigureServices вызывается до Configure в Startup.Вы, кажется, создаете свою конфигурацию после того, как уже пытаетесь получить к ней доступ.

Переместите код сборки, который будет вызываться ранее, в потоке

private IConfiguration Configuration;

public Startup(IHostingEnvironment env) {
    var builder = new ConfigurationBuilder()
       .SetBasePath(env.ContentRootPath)
       .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
       .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true);

    Configuration = builder.Build(); //<--
}

public void ConfigureServices(IServiceCollection services) {

    services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
    services.AddDbContext<ApplicationDBContext>(options => 
        options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))
    );
}

public void Configure(IApplicationBuilder app, IHostingEnvironment env) {

    if (env.IsDevelopment()) {
        app.UseDeveloperExceptionPage();
    } else {
        app.UseHsts();
    }

    app.UseHttpsRedirection();
    app.UseMvc();
}

Вы должны удалить переопределение OnConfiguring изDbContext, поскольку для него не настроен базовый путь, поэтому, скорее всего, файл настроек не найден.

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