【问题标题】:Config connection string in .net core 6在 .net core 6 中配置连接字符串
【发布时间】:2021-10-29 00:12:56
【问题描述】:
我正在尝试使用 Sql Server 连接到我的 asp.net 核心 Web api 应用程序(Visual Studio 2022 Preview 中的 .net 6)。并且我尝试使用下面的代码来配置 Startup 类中的连接字符串。
services.AddDbContext<DEMOWTSSPortalContext>(options => options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
但在 .net 6 中,我认识到 Startup 和 Program 类合并为一个类。并且上面的代码在.net 6 中不可用。AddDbContext 无法识别。那么您对此次更新以及如何在 .net 6 中配置 ConnectionStrings 有任何想法或文档吗?
【问题讨论】:
标签:
c#
asp.net
asp.net-core
visual-studio-2022
【解决方案1】:
.NET6 中的Configuration.GetConnectionString(string connName) 在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"));
});
【解决方案2】:
.Net 6 简化了很多任务并引入了WebApplicationBuilder,这反过来又让您可以访问新的配置生成器和服务集合 em>
var builder = WebApplication.CreateBuilder(args);
属性
-
Configuration : 供应用程序编写的配置提供程序的集合。这对于添加新的配置源和提供程序很有用。
-
Environment:提供有关应用程序正在运行的网络托管环境的信息。
-
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