asp.net core 2.0 - 值不能为空。参数名称: connectionString

标签 asp.net asp.net-mvc asp.net-core

添加迁移时,程序包管理器控制台中出现以下错误

Value cannot be null. Parameter name: connectionString

这是我的创业公司:

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"]);
            });
        }
    }
}

程序类别:

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"
  }
}

有趣的是,如果我运行该应用程序,它会显示“Hello World”,但是当添加迁移时,它找不到连接字符串。有人可以在这里照亮一些吗?谢谢。

最佳答案

当找不到连接字符串时会出现此问题。

Startup 类中可能有以下代码:

public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<BenchmarkContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("yourConnectionString name from appsettings.json")));
    }

这些方法可以解决您的问题:

1-而不是 Configuration.GetConnectionString("yourConnectionString name from appsettings.json(indevelopment mode: 'appsettings.Development.json')") 只需放置您的连接字符串。

public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<BenchmarkContext>(options =>
  options.UseSqlServer("Data Source=.;Initial Catalog=Benchmark;Persist Security Info=True;User ID=****;Password=****"));
    }

2-如果您要使用配置文件,请将这些代码添加到 Startup 类中:

public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }
public IConfiguration Configuration;

public void ConfigureServices(IServiceCollection services)
    {
        services.AddDbContext<BenchmarkContext>(options =>
            options.UseSqlServer(Configuration.GetConnectionString("TestConnection")));
    }

Appsettings.json 文件(在开发模式下:'appsettings.Development.json'):

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

之后在程序包管理器控制台中执行“add-migration name”命令

关于asp.net core 2.0 - 值不能为空。参数名称: connectionString,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46010003/

相关文章:

c# - 如何在母版页中创建创建变量/属性,并让子页面访问它们?

c# - 绑定(bind) C#、ASP.net 后在 gridview 中添加新行

asp.net - 保护 ASP.NET MVC 应用程序中的 ajax 调用的安全

c# - 始终选中 ASP.net 复选框

c# - 在 asp.net MVC 中为网站提供更好的用户体验

c# - ASP.NET Core 服务范围工厂未定义行为

asp.net-mvc - 如何在 Visual Studio MVC View 中关闭大括号和编码元素的自动更正

asp.net-mvc - 剑道模板在网格中无效

asp.net - AspNet.Security.OpenIdConnect 与 OAuthAuthorizationProvider

asp.net-core - ValidationSummary.ModelOnly 失败,但 ValidationSummary.All 有效