简体   繁体   中英

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

I add appsettings.json in order to get connection string but I cannot get my connection string. Here is my code.

public class MovieTheaterDBContextFactory : IDesignTimeDbContextFactory<MovieTheaterDBContext>
{
    public MovieTheaterDBContext CreateDbContext(string []Args)
    {
        IConfigurationRoot configuration = new ConfigurationBuilder()
            .SetBasePath(Directory.GetCurrentDirectory())
            .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
            .Build();

        var ConnectionString = configuration.GetConnectionString("MovieTheaterDBContext");
        //var ConnectionString = "Server=DESKTOPM4\\SQLEXPRESS;Database=MovieTheaterManagerment;Trusted_Connection=True;";
        var optionsBuilder = new DbContextOptionsBuilder<MovieTheaterDBContext>();
        optionsBuilder.UseSqlServer(ConnectionString);

        return new MovieTheaterDBContext(optionsBuilder.Options);
    }

   
}

appsettings.json:

{
  "ConnectionStrings":
  {
    "MovieTheaterDBContext": "Server=DESKTOPM4\\SQLEXPRESS;Database=EshopSolution;Trusted_Connection=True;"
  }
}

Update: It is my mistake, I have not set this project as startup project.So it can't find appsettings.json.

Right click on appsettings.json file and go to the properties and change "Copy to output directory" option to "Copy always"

Check that your appSettings.json file is in the directory where all your projects file are located. Where the.csproj is located.

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