Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
231 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.

question from:https://stackoverflow.com/questions/46010003/asp-net-core-2-0-value-cannot-be-null-parameter-name-connectionstring

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

1 Reply

0 votes
by (71.8m points)

This problem occurred when the connectionstring can't be found.

Probably you have following codes 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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...