简体   繁体   中英

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.

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

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.

I had such issue when load tesing the service (I recommend it to all) and had ~3/1000 requests with errors, so I changed

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

to

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

So it reads connections string 1 time and doesn't use Configuration on every request. And now 100% requests are successful. But it seems to be a bug in .Net Core

I found my own problem.

I have an AppDbContextFactory class which inherits IDesignTimeDbContextFactory. Deleting this class resolves this issue.

I had the same problem, because I was using the default value in Startup.cs . I just edited Configuration property from:

public IConfiguration Configuration { get; }

to:

public IConfiguration Configuration;

and it worked! If someone say why would be appreciated.

I had had a similar issue because of the following reasons:

  • appsettings.json was not included in the project
  • I was running the project from the path which did not contain appsettings.json

我遇到了同样的错误,并通过将“ConnectionStrings”移动到 appsettings.json 文件中的第一个变量来解决它。

Probably, the issue is with your DotNetCliToolReference from the csproj file. If you migrate the project from an older version of asp.net core, the DotNetCliToolReference is not automatically updated. Update the yourproject.csproj file to use the 2.0.0 version of the CLI as shown in the snippet bellow:

<ItemGroup>

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

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

dotnet ef database update -v

Also, recheck your Microsoft.EntityFrameworkCore nuget packages to reference the 2.0.0 version. Remove or update older EF packages. The minimum are:

  • Microsoft.EntityFrameworkCore.SqlServer

  • Microsoft.EntityFrameworkCore.Design

both 2.0.0 at this moment.

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

I had the same problem and what it is the I had to make sure that the name of the connection matches:

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

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

After I fixed this, everything was fine.

I had a similar issue. I had a typo in my appsettings.json . Changing ConnectionsStrings to ConnectionStrings did it for me!

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

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 program class looks like the following:

public class Program
{
    public static void Main(string[] args)
    {
        BuildWebHost(args).Run();
    }

    public static IWebHost BuildWebHost(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseStartup<Startup>()
            .Build();
}

I have solved my issue by setting right base path. The problem is the migrations or anything else from different packages uses wrong path to the appsetting.json file. Not sure if it's an official issue.

I have just changed 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's missing there.

This 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 as reference where to replace.

I had a similar problem when I specified the ".UseContentRoot" as the current process path.

public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
        WebHost.CreateDefaultBuilder(args)
            .UseUrls("http://*:3001")
            .UseStartup<Startup>()
            .UseContentRoot(Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName));

thus when running Add-Migration the process path is different from the project bin path therefore the process can't find the appsettings.json file. when I removed the ".UseContentRoot" line the migration was successful

I'm stupid and I had typo

{
  "Conn'ce'tionStrings": {
    "DefaultConnection": "Data source=datingapp.db"
  },

changed it to

{
  "ConnectionStrings": {
    "DefaultConnection": "Data source=datingapp.db"
  },

我的问题是当我试图在 netcoreapp2.1 文件夹中运行 App.dll 时,但正确的文件夹是 netcoreapp2.1\\publish\\

如果您之前在 appsettings 文件中重命名了连接字符串,并且在 DesignTimeDbContextFactory 类中省略了重命名(如果您的项目中有它)并且由实体框架检查,那么您可能会在此问题中运行。

If you are using an IDesignTimeDbContextFactory, you will need to add a default constructor to it with no parameters. Try something like this:

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

    _connectionString = configuration.GetConnectionString("ConnectionStringName");
}

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

I figured I would add what it was for me. I had followed a popular tutorial to add appsettings.json and dependency injection to a console application. I did not realize in the setup that it referenced the current directory and was using that to set the base path of the configuration builder. It worked fine when I was running locally, but as soon as I tried to deploy and have a SQL scheduled job run the command it was taking the directory where the command was being entered, not where the DLL was so it wasn't finding my appsettings.json file. I simply removed the lines that dealt with getting the current directory and setting that as the base path and it works fine. It seems like it defaults to the same folder as the DLL.

I had this problem due to a difference in connectionstring of appsetting.json file, and the GetConnectionString(connectionstrings) parameter in startup.cs . Once I removed extra s in startup.cs , the problem disappeared.

Check if ASPNETCORE_ENVIRONMENT variable is set up on the server correctly. Depending on that environment it may be taking appsettings.json instead of appsettings.Staging.json or appsettings.Production.json .

In my case i was using configuration["DbContext"]

 services.AddDbContext<AstroBhaskarDbContext>(option =>
 {
     option.UseSqlServer(configuration["DbContext"]);
 });

then i replaced configuration["DbContext"] to configuration.GetConnectionString("DbContext") as below

  services.AddDbContext<AstroBhaskarDbContext>(option =>
  {
     option.UseSqlServer(configuration.GetConnectionString("DbContext"));
  });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM