为什么我的 ASP.NET 核心 SQL 服务器快速连接字符串出现错误?

Why am I getting an error in my ASP.NET Core SQL Server Express Connection String?

我最近启动了一个新的 ASP.NET 核心 Web 应用程序,我想将它连接到我的本地 SQLExpress 数据库。我一直在关注文档,但是当它试图在

读取我的连接字符串时,我收到了 "Value cannot be null" 的错误

options.UseSqlServer(configuration.GetConnectionString("DefaultConnection")

到目前为止,这是我的代码。在 Startup.cs 中,我有以下设置:

using Microsoft.AspNetCore.Builder;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.DependencyInjection;
using Blondie.CoreApiSql.Models;
using Microsoft.Extensions.Configuration;

namespace Blondie.CoreApiSql
{
    public class Startup
    {
        private readonly IConfiguration configuration;
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddDbContext<DatabaseContext>
                (options => options.UseSqlServer(configuration.GetConnectionString("DefaultConnection")));
            services.AddMvc();
        }
        public void Configure(IApplicationBuilder app)
        {
            app.UseMvc();
        }
    }
}

当您 运行 应用程序时,会在以下行触发错误:

services.AddDbContext<DatabaseContext> (options => options.UseSqlServer(configuration.GetConnectionString("DefaultConnection")));

我已经按照文档中的描述在 appsettings.json 中定义了连接字符串,如下所示:

{
    "ConnectionStrings": {
        "DefaultConnection": "Data Source=DESKTOP-PC009\SQLEXPRESS;Database=Senua;Trusted_Connection=True;MultipleActiveResultSets=true"
    },
    "Logging": {
      "IncludeScopes": false,
      "Debug": {
        "LogLevel": {
          "Default": "Warning"
        }
      },
      "Console": {
        "LogLevel": {
          "Default": "Warning"
        }
      }
    }
  }

我已经创建了 Senua 数据库,其中 table 没有数据。我的数据库使用 windows 身份验证。

我用我的单曲 table.

按照以下方式定义了我的数据库上下文
public class DatabaseContext : DbContext
{
    public DatabaseContext(DbContextOptions<DatabaseContext> options) 
        : base(options)
    {
    }
    public DbSet<Hellheim> Hellheim { get; set; }
}

据我了解,如果您未能在 appsettings.json 文件中定义连接字符串,但我已经添加了它,那么此错误通常只会出现,以前有人遇到过这个问题吗?

定义一个值并将其分配给 IConfiguration 的配置,并且需要一个值。 在构造函数中定义依赖注入

public Startup(IConfiguration configuration)
    {
        this.configuration = configuration;
    }