c# - 为什么我的 ASP.NET Core SQL Server Express 连接字符串出现错误?

标签 c# sql-server asp.net-core connection-string

我最近启动了一个新的 ASP.NET Core Web 应用程序,我想将其连接到我的本地 SQLExpress 数据库。我一直在关注文档,但当它尝试读取我的连接字符串时,出现“值不能为空”错误

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数据库中有一个表,但没有数据。我的数据库使用 Windows 身份验证。

我已通过以下方式使用单个表定义了数据库上下文。

public class DatabaseContext : DbContext
{
    public DatabaseContext(DbContextOptions<DatabaseContext> options) 
        : base(options)
    {
    }
    public DbSet<Hellheim> Hellheim { get; set; }
}

据我所知,只有当您未能在 appsettings.json 中定义连接字符串时,此错误通常才会明显。文件,但我已经添加了它,以前有人遇到过这个问题吗?

最佳答案

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

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

关于c# - 为什么我的 ASP.NET Core SQL Server Express 连接字符串出现错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49695987/

相关文章:

c# - 为什么匿名用户试图访问/admin/host/synctriggers?

php - 使用 PDO ODBC SQL Server 连接时定义编码?

c# - 使用 ExceptionHandler PipeLine 时,ASP.NET Core 返回 404 而不是 500

c# - Azure Webjob 服务的 Microsoft.Azure.ServiceBus.Message 支持

c# - Asp.net 核心问题中的分页,只得到 10 个项目不能让它更快?

C# 获取 Windows CD key

sql - SQL 中聚合函数的除法不符合预期

c# - Linq to SQL 不将数据插入数据库

c# - 如何将文件复制到 Azure Function bin 文件夹中?

asp.net-core - ASP.NET 5 (MVC6) 如何为用户提供种子