【问题标题】:asp.net core 2.0 - Value cannot be null. Parameter name: connectionStringasp.net core 2.0 - 值不能为空。参数名称:连接字符串
【发布时间】:2018-02-11 02:17:03
【问题描述】:

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

值不能为空。参数名称:连接字符串

这是我的创业公司:

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”,但是在添加迁移时它找不到连接字符串。有人可以在这里点亮一些灯吗?谢谢。

【问题讨论】:

  • AppDbContext 的构造函数是什么样的?见docs.microsoft.com/en-us/ef/core/miscellaneous/…。您不应使用无参数构造函数,而应使用带有 DbContextOptions 的默认构造函数。
  • @zuckerthoben 谢谢,这就是我使用的。 'public AppDbContext(DbContextOptions options) : base(options) { }"

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


【解决方案1】:

问题可能出在 csproj 文件中的 DotNetCliToolReference 上。如果从旧版本的 asp.net core 迁移项目,DotNetCliToolReference 不会自动更新。 更新 yourproject.csproj 文件以使用 2.0.0 版本的 CLI,如下面的 sn -p 所示:

<ItemGroup>

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

从项目文件夹中重新运行带有 -v 开关的 dotnet 命令以查看结果

dotnet ef database update -v

另外,请重新检查您的 Microsoft.EntityFrameworkCore nuget 包以引用 2.0.0 版本。删除或更新旧的 EF 包。最低要求是:

  • Microsoft.EntityFrameworkCore.SqlServer

  • Microsoft.EntityFrameworkCore.Design

目前都是 2.0.0。

【讨论】:

  • 这似乎没有帮助
【解决方案2】:

在尝试为 ASP.NET Core 2.0 Web Api 使用新创建的项目后,我遇到了类似的问题。据我发现,问题的原因是没有添加为开发环境指定的应用程序设置。我通过将启动文件更新为以下内容来修复它:

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();
}

在我的例子中,程序类如下所示:

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

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

【讨论】:

  • 嗨,谢谢,但这似乎也无济于事。我确信在 core 2.0 中你可以将 appsettings 构建移动到 program.class,而启动构造函数只需要进行配置注入。 – 韩冰 7 小时前
  • @BingHan 是的,你可以这样做。但这就是问题的根源。只有在 BuildWebHost 实例化时才会添加您的应用程序设置。大多数工具不需要运行您的应用程序来执行它们的操作。相反,他们可以使用您的启动文件创建假主机或类似的东西。在这种情况下,IConfiguration 只是简单地解析为具有空配置的实例。
  • 我找到了问题,感谢您的帮助!
【解决方案3】:

我发现了自己的问题。

我有一个继承 IDesignTimeDbContextFactory 的 AppDbContextFactory 类。删除此类可解决此问题。

【讨论】:

  • 还有另一种解决方案,而不是完全删除上下文工厂。将以下默认构造函数添加到类:``` public DesignTimePrioritizedListDbContextFactory() { IConfigurationRoot configuration = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddEnvironmentVariables() .AddJsonFile("appsettings.json", false, true) 。建造(); _connectionString = configuration.GetConnectionString(Startup.SqlConnectionSettingName); } ```
  • 是的,不是删除它,而是修复它。缺少的连接字符串正是来自这里。
【解决方案4】:

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

可能你在 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"),只需输入您的连接字符串。

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

Appsetting.json 文件:

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

之后在包管理器控制台中执行'add-migration name'命令

【讨论】:

  • 我写的是“ConnectionString”而不是“ConnectionStrings”,最后一个“s”是我的错
  • @RezaBayat 同样:D
  • 我添加到 Appsettings.Development.json 文件而不是 Appsettings.json 文件。因此它不起作用。
【解决方案5】:

我遇到了同样的问题,但我的解决方案要简单得多。我所做的只是将 appsettings.json 的顺序从:

{
  "Message": "Hello World",
  "ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\MSSQLLocalDB;Database=NotMyFault;Trusted_Connection=True;MultipleActiveResultSets=true"
  }
}

到:

{
   "ConnectionStrings": {
    "DefaultConnection": "Server=(localdb)\\MSSQLLocalDB;Database=NotMyFault;Trusted_Connection=True;MultipleActiveResultSets=true"
  },
  "Message": "Hello World"
}

我怀疑 appsettings.json 文件中有参数的顺序/顺序。

【讨论】:

  • 这正是我遇到的问题。显然它希望ConnectionStrings 在顶部。这是否记录在某处?
  • 同样的事情!负载测试服务时遇到此问题。感谢您的解决方案。有没有人向 Microsoft 报告过这个错误?
  • 这里也一样。必须将连接字符串放在 json 文件的顶部,然后它就开始工作了。谢谢!
  • 我刚刚在 VS 2019、EF Core、.NET 5 中遇到了同样的问题。这确实应该得到解决。如果没有这个答案,我不确定我是否会弄明白。
【解决方案6】:

我遇到了同样的问题,因为我使用的是 Startup.cs 中的默认值。 我刚刚从以下位置编辑了配置属性:

public IConfiguration Configuration { get; }

到:

public IConfiguration Configuration;

它成功了! 如果有人说为什么会很感激。

【讨论】:

  • 这对我有用,仍在学习 .net core 2.0,我遵循的指南说要设置方法,我认为它应该由依赖注入提供,但如果你做到了一个可以设置的属性,它可以工作
  • 默认 ASP.Net Core 脚手架在没有设置器的情况下生成属性。需要添加它,但这对我来说还不足以解决我遇到的 OP 问题。
【解决方案7】:

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

【讨论】:

    【解决方案8】:

    由于以下原因,我遇到了类似的问题:

    • appsettings.json 未包含在项目中
    • 我从不包含 appsettings.json 的路径运行项目

    【讨论】:

    • 就我而言,我在 appsettings.json 中拼错了一些内容,但您的回答帮助我找到了问题。
    【解决方案9】:

    我通过设置正确的基本路径解决了我的问题。问题是来自不同包的迁移或其他任何内容使用了错误的 appsetting.json 文件路径。不确定这是否是官方问题。

    我刚刚将我的 Startup.cs 更改如下:

    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();
        }
    

    之后,如果您的 appsettings.json 丢失,您只需将其复制到正确的位置即可。

    【讨论】:

      【解决方案10】:

      这对我来说完美无缺:

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

      注释部分仅作为替换位置的参考。

      【讨论】:

        【解决方案11】:

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

        【讨论】:

          【解决方案12】:

          我在对服务进行负载测试时遇到了这样的问题(我向所有人推荐)并且有大约 3/1000 个错误请求, 所以我改变了

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

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

          因此它会读取连接字符串 1 次,并且不会对每个请求都使用配置。现在 100% 的请求都成功了。 但这似乎是.Net Core中的一个错误

          【讨论】:

            【解决方案13】:

            另一种情况是您可以设置配置。在 appsettings.json 而不是 appsettings.Development.json

            中设置连接字符串

            【讨论】:

              【解决方案14】:

              如果您使用的是 IDesignTimeDbContextFactory,则需要向其添加不带参数的默认构造函数。试试这样的:

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

              【讨论】:

                【解决方案15】:

                我遇到了同样的问题,我必须确保连接的名称匹配:

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

                which ****ConnectionStrings:DefaultConnection*** 这是我遇到问题的地方。 确保 Startup.cs 和 appsettings.json 中的内容相同(Vs 2019 中的 appsettings.Development.json)

                在我解决这个问题后,一切都很好。

                【讨论】:

                • 对我来说,问题是我在 appsettings.development.json 文件中定义了连接字符串,但 appsettings.json 的顶部缺少它。
                【解决方案16】:

                对我来说,出于某种原因,我使用的是 appSettings.json 而不是 appsettings.json(不太确定 VS 是否对新创建的项目进行了此操作,或者我已将其重命名为该项目)。一旦我更改了名称,它就可以正常工作了。

                【讨论】:

                  【解决方案17】:

                  我想我会添加适合我的东西。我按照一个流行的教程将 appsettings.json 和依赖注入添加到控制台应用程序。我在设置中没有意识到它引用了当前目录并使用它来设置配置生成器的基本路径。当我在本地运行时它运行良好,但是一旦我尝试部署并让 SQL 计划作业运行命令,它就会进入输入命令的目录,而不是 DLL 所在的目录,所以它没有找到我的appsettings.json 文件。我只是删除了处理获取当前目录并将其设置为基本路径的行,它工作正常。它似乎默认为与 DLL 相同的文件夹。

                  【讨论】:

                    【解决方案18】:

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

                    【讨论】:

                      【解决方案19】:

                      当我将“.UseContentRoot”指定为当前进程路径时,我遇到了类似的问题。

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

                      因此,在运行 Add-Migration 时,进程路径与项目 bin 路径不同,因此进程找不到 appsettings.json 文件。 当我删除“.UseContentRoot”行时,迁移成功

                      【讨论】:

                        【解决方案20】:

                        由于appsetting.json 文件的connectionstringstartup.cs 中的GetConnectionString(connectionstrings) 参数不同,我遇到了这个问题。一旦我在startup.cs 中删除了额外的s,问题就消失了。

                        【讨论】:

                          【解决方案21】:

                          我遇到了类似的问题。我的appsettings.json 中有错字。将ConnectionsStrings 更改为ConnectionStrings 为我做了这件事!

                          【讨论】:

                            【解决方案22】:

                            我很笨,我有错字

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

                            改成

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

                            【讨论】:

                              【解决方案23】:

                              检查ASPNETCORE_ENVIRONMENT 变量是否在服务器上正确设置。根据该环境,它可能会采用appsettings.json 而不是appsettings.Staging.jsonappsettings.Production.json

                              【讨论】:

                                猜你喜欢
                                • 1970-01-01
                                • 2019-11-06
                                • 2020-10-24
                                • 1970-01-01
                                • 1970-01-01
                                • 2020-01-29
                                • 2021-01-29
                                • 2021-07-26
                                • 1970-01-01
                                相关资源
                                最近更新 更多