Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

Value cannot be null. Parameter name: connectionString

This is my startup:

namespace MyProject {     public class Startup     {         public IConfiguration Configuration { get; set; }         public Startup(IConfiguration config)         {             Configuration = config;         }          public void ConfigureServices(IServiceCollection services)         {             services.AddDbContextPool<AppDbContext>(options =>                              options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));             services.AddTransient<IDevRepo, DevRepo>();             services.AddMvc();             services.AddMemoryCache();             services.AddSession();         }          public void Configure(IApplicationBuilder app, IHostingEnvironment env)         {             if (env.IsDevelopment())             {                 app.UseDeveloperExceptionPage();             }             app.UseStatusCodePages();             app.UseStaticFiles();             app.UseMvcWithDefaultRoute();             app.Run(async (context) =>             {                 await context.Response.WriteAsync(Configuration["Message"]);             });         }     } } 

program class:

public class Program {     public static void Main(string[] args)     {         BuildWebHost(args).Run();     }      public static IWebHost BuildWebHost(string[] args) =>         WebHost.CreateDefaultBuilder(args)             .ConfigureAppConfiguration((context, builder) => builder.SetBasePath(context.HostingEnvironment.ContentRootPath)                        .AddJsonFile("appsettings.json")                        .Build())              .UseStartup<Startup>()             .Build(); } 

appsettings.json:

{   "Message": "Hello World",   "ConnectionStrings": {     "DefaultConnection": "Server=(localdb)\\MSSQLLocalDB;Database=NotMyFault;Trusted_Connection=True;MultipleActiveResultSets=true"   } } 

Interestingly if I run the app, it displays "Hello World", but when add migration it cannot find connectionString. Can someone please shed some lights here? Thanks.

like image 575
Bing Han Avatar asked Sep 02 '17 02:09

Bing Han


2 Answers

This problem occurred when the connection string can't be found.

Probably you have the following code in Startup class:

public void ConfigureServices(IServiceCollection services)     {         services.AddDbContext<BenchmarkContext>(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<BenchmarkContext>(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<BenchmarkContext>(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

like image 126
Iman Bahrampour Avatar answered Sep 19 '22 14:09

Iman Bahrampour


I had the same issue, but my solution was a lot simpler. All I did was to change the order of the appsettings.json from:

{   "Message": "Hello World",   "ConnectionStrings": {     "DefaultConnection": "Server=(localdb)\\MSSQLLocalDB;Database=NotMyFault;Trusted_Connection=True;MultipleActiveResultSets=true"   } } 

to:

{    "ConnectionStrings": {     "DefaultConnection": "Server=(localdb)\\MSSQLLocalDB;Database=NotMyFault;Trusted_Connection=True;MultipleActiveResultSets=true"   },   "Message": "Hello World" } 

I have a suspicion that there is a sequence/order of parameters in the appsettings.json file.

like image 23
Jay Avatar answered Sep 22 '22 14:09

Jay