.net core 6 中的配置连接字符串

Config connection string in .net core 6

我正在尝试使用 SQL 服务器连接到我的 ASP.NET Core Web API 应用程序(Visual Studio 2022 预览版中的 .NET 6)。我尝试使用以下代码在 Startup class 中配置连接字符串,就像我以前那样。

services.AddDbContext<DEMOWTSSPortalContext>(options =>
                options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));

但在 .NET 6 中,我认识到 StartupProgram class 合并为一个 class。上面的代码在 .NET 6 中不可用。AddDbContext 无法识别。那么关于此更新以及如何在 .NET 6 中配置连接字符串,您有任何想法或文档吗?

.Net 6 简化了很多任务并引入了 WebApplicationBuilder,这反过来又让您可以访问新的 Configuration builder服务集合

var builder = WebApplication.CreateBuilder(args);

属性

  • Configuration :要组成的应用程序的配置提供程序集合。这对于添加新的配置源和提供程序很有用。

  • Environment :提供有关应用程序所在的 Web 托管环境的信息 运行。

  • Host :用于配置主机特定属性的 IHostBuilder,但不用于构建。要在配置后构建,请调用 Build()。

  • Logging :用于编写应用程序的日志记录提供程序的集合。这对于添加新的日志记录提供程序很有用。

  • Services :要组成的应用程序的服务集合。这对于添加用户提供或框架提供的服务很有用。

  • WebHost :用于配置服务器特定属性的 IWebHostBuilder,但不用于构建。要在配置后构建,请调用 Build()。

添加一个 DbContext 到 Di Container 并配置它,有很多选项,但最直接的是

builder.Services.AddDbContext<SomeDbContext>(options =>
{
   options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"));
});

Nugets 包

  • Microsoft.EntityFrameworkCore
  • Microsoft.EntityFrameworkCore.SqlServer 使用 UseSqlServer

Configuration.GetConnectionString(string connName) in .NET6 is under builder:

var builder = WebApplication.CreateBuilder(args);
string connString = builder.Configuration.GetConnectionString("DefaultConnection");

AddDbContext() 也在 builder.Services:

builder.Services.AddDbContext<YourContext>(options =>
{
    options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"));

});