asp.net core 2.0 - Value cannot be null. Parameter name: connectionString

后端 未结 22 1933
时光取名叫无心
时光取名叫无心 2020-12-13 10:00

I had the following error in package manager console when Add-Migration

Value cannot be null. Parameter name: connectionString

22条回答
  •  暗喜
    暗喜 (楼主)
    2020-12-13 10:05

    This problem occurred when the connectionstring can't be found.

    Probably you have following codes in Startup class:

    public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext(options =>
                options.UseSqlServer(Configuration.GetConnectionString("yourConnectionString name from appsettings.json")));
        }
    

    These methods solve your problem:

    1- Instead of Configuration.GetConnectionString("yourConnectionString name from appsettings.json") just put your connectionstring.

    public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext(options =>
      options.UseSqlServer("Data Source=.;Initial Catalog=Benchmark;Persist Security Info=True;User ID=****;Password=****"));
        }
    

    2- If you are going to use the Configuration file add these codes to Startup class:

    public Startup(IConfiguration configuration)
        {
            Configuration = configuration;
        }
    public IConfiguration Configuration;
    
    public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext(options =>
                options.UseSqlServer(Configuration.GetConnectionString("TestConnection")));
        }
    

    Appsetting.json file:

    {
      "ConnectionStrings": {
        "TestConnection": "Data Source=.;Initial Catalog=Benchmark;Persist Security Info=True;User ID=****;Password=****"
      }
    }
    

    After that execute 'add-migration name' command in Package Manager Console

提交回复
热议问题