While I'm working ins asp.net core 3.1 getting this error Value cannot be null. (Parameter 'connectionString')

Viewed 173

System.ArgumentNullException: 'Value cannot be null. (Parameter 'connectionString')

I am getting this error I think that problem brings from appsetting.json but I can't find it

 "AllowedHosts": "*",
    "ConnectionString": {
        "EmployeeDbConnection" : "server=(localdb)\\MSSQLLocalDB;database=EmployeeDB;Trusted_Connection=true;"
    }

Error bring from _config.GetConnectionString("EmployeeDbConnection)

public Startup(IConfiguration config)
        {
            _config = config;
        }
        // This method gets called by the runtime. Use this method to add services to the container.
        // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
        public void ConfigureServices(IServiceCollection services)
        {
           
            services.AddDbContextPool<AppDbContext>(options => options.UseSqlServer(_config.GetConnectionString("EmployeeDbConnection")));
            
            services.AddScoped<IEmployeeRepository, SqlServerRepository>();
            services.AddMvc(options => options.EnableEndpointRouting = false).AddXmlSerializerFormatters();
        }
2 Answers

The reason is in your appsettings.json:

Change the code to(ConnectionString to ConnectionStrings):

 "AllowedHosts": "*",
   "ConnectionStrings": {
    "EmployeeDbConnection" : "server=(localdb)\\MSSQLLocalDB;database=EmployeeDB;Trusted_Connection=true;"
}

You can also try what I wrote below. It solved my problem.

MY appsettings.json

  "ConnectionStrings": {
"DefaulConnection": "Data source=skinet.db"} 

I used a much simpler structure while solving the problem. startup.cs :

services.AddDbContext<StoreContext>(x => 
x.UseSqlite(_config.GetConnectionString("DefaultConnection")));

Writing the following instead of the above may solve the problem.

services.AddDbContext<StoreContext>(x =>
x.UseSqlite(("DefaultConnection")));
Related