Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
472 views
in Technique[技术] by (71.8m points)

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...