Asp.net core 2.0 - Value cannot be null. Parameter Name: connectionString

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

The value cannot be null. Parameter Name: connectionString

This is my launch:

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 application, it will display "Hello World", but when adding the migration it will not be able to find the connectionString. Can someone shed some light here? Thanks.

+26
source share
17 answers

I found my own problem.

I have an AppDbContextFactory class that inherits IDesignTimeDbContextFactory. Removing this class fixes this problem.

+1
source

This problem occurred when the connection string could not be found.

You probably have the following codes in the 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 enter the connection string.

 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 intend to use the configuration file, add these codes to the 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"))); } 

Apps.txt file:

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

After that, run the add-redirect name command in the package manager console

+22
source

I had the same problem, but my solution was much simpler. All I did was reorder appsettings.json:

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

in

 { "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.

+9
source

I had the same problem because I used the default value in Startup.cs . I just edited the configuration property from:

 public IConfiguration Configuration { get; } 

so that:

 public IConfiguration Configuration; 

and it worked! If someone says why it will be appreciated.

+3
source

Perhaps the problem is with your DotNetCliToolReference from the csproj file. If you migrate a project from an older version of the asp.net kernel, the DotNetCliToolReference is not updated automatically. Update yourproject.csproj to use version 2.0.0 of the CLI, as shown in the following snippet:

 <ItemGroup> ... <DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="2.0.0" /> </ItemGroup> 

Repeat, from the project folder, the dotnet command with the -v switch to see the results

 dotnet ef database update -v 

Also, double-check Microsoft.EntityFrameworkCore nuget packages for a link to version 2.0.0. Uninstall or upgrade old EF packages. Minimum:

  • Microsoft.EntityFrameworkCore.SqlServer

  • Microsoft.EntityFrameworkCore.Design

both 2.0.0 at the moment.

+2
source

I had a similar problem for the following reasons:

  • appsettings.json was not included in the project
  • I ran the project along a path that did not contain appsettings.json
+2
source

I had a similar problem after trying to use a newly created project for ASP.NET Core 2.0 Web Api. As I understand it, the cause of the problem was that the application settings specified for the development environment were not added. I fixed it by updating the startup file as follows:

 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) .AddEnvironmentVariables(); this.Configuration = builder.Build(); } 

In my case, the program class is as follows:

 public class Program { public static void Main(string[] args) { BuildWebHost(args).Run(); } public static IWebHost BuildWebHost(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>() .Build(); } 
+1
source

I solved my problem by setting the correct base path. The problem is that migrations or anything else from different packages uses the wrong path to the appsetting.json file. Not sure if this is an official question.

I just modified my Startup.cs as follows:

 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, reloadOnChange: true) .AddEnvironmentVariables(); Configuration = builder.Build(); } 

After that, you just need to copy your appsettings.json to the right place if it is not there.

+1
source

I had such a problem during stress testing of the service (I recommend it to everyone) and there were ~ 3/1000 requests with errors, so I changed

 services.AddDbContextPool<AppDbContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); 

in

 string connectionString = Configuration.GetConnectionString("DefaultConnection"); services.AddDbContextPool<AppDbContext>(options => options.UseSqlServer(connectionString)); 

Thus, it reads the connection string 1 time and does not use the configuration with every request. And now 100% of the requests were successful. But there seems to be a bug in .Net Core

+1
source

My problem was when I tried to run App.dll in the netcoreapp2.1 folder, but the correct folder is netcoreapp2.1 \ publish \

0
source

It worked flawlessly for me:

 public IConfiguration Configuration; public void ConfigureServices(IServiceCollection services) { services.AddDbContext<ApplicationDbContext.ApplicationDbContext>(options => //options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection"))); options.UseSqlServer("Server=serverAddress; Database=dbName; user=username; password=pswd")); } 

The commented part is just a replacement link.

0
source

If you previously renamed the connection string in the appsettings file and did not specify its renaming in the DesignTimeDbContextFactory class (if it is in your project), and this is verified by the Entity platform, then you can run this problem.

0
source

Another scenario might be where you set up the configuration. set connection string in appsettings.jso n instead of appsettings.Development.json

0
source

If you use IDesignTimeDbContextFactory, you will need to add a default constructor without parameters to it. Try something like this:

 public DbContextFactory() { IConfigurationRoot configuration = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddEnvironmentVariables() .AddJsonFile("appsettings.json", false, true) .Build(); _connectionString = configuration.GetConnectionString("ConnectionStringName"); } 
0
source

I had the same problem, and that I had to make sure the connection name matches:

  services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1); services.AddDbContext<MyContext>(options => options.UseSqlServer(Configuration["ConnectionStrings:DefaultConnection"])); 

which **** ConnectionStrings: DefaultConnection *** this was where I had the whole problem. Make sure the same in Startup.cs and appsettings.json (appsettings.Development.json in Vs 2019)

After I fixed it, everything was fine.

0
source

The problem is not changing the current directory. This solves it. http://life-of-dev.sblo.jp/article/186312617.html

0
source

For me it was that I had appSettings.json instead of appsettings.json for some reason (not quite sure if VS did this with a newly created project, or I renamed it to this). As soon as I changed my name, everything worked fine.

0
source

Source: https://habr.com/ru/post/1271443/


All Articles