con*_*pan 85 c# asp.net-core asp.net-core-6.0 visual-studio-2022
我正在尝试使用 SQL Server 连接到我的 ASP.NET Core Web API 应用程序(Visual Studio 2022 预览版中的 .NET 6)。Startup我尝试像以前一样使用以下代码在类中配置连接字符串。
services.AddDbContext<DEMOWTSSPortalContext>(options =>
options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
Run Code Online (Sandbox Code Playgroud)
但在 .NET 6 中,我认识到Startup和Program类已合并为一个类。并且上面的代码在.NET 6中不可用。AddDbContext无法识别。那么您对此次更新以及如何在 .NET 6 中配置连接字符串有任何想法或文档吗?
小智 118
.NET6 中的 Configuration.GetConnectionString(string connName) 位于构建器下:
var builder = WebApplication.CreateBuilder(args);
string connString = builder.Configuration.GetConnectionString("DefaultConnection");
Run Code Online (Sandbox Code Playgroud)
AddDbContext() 也在 builder.Services 下:
builder.Services.AddDbContext<YourContext>(options =>
{
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"));
});
Run Code Online (Sandbox Code Playgroud)
AAA*_*ddd 98
.Net 6简化了许多任务并引入了WebApplicationBuilder这些任务,从而使您可以访问新的配置构建器和服务集合
var builder = WebApplication.CreateBuilder(args);
Run Code Online (Sandbox Code Playgroud)
特性
Configuration:供应用程序组成的配置提供程序的集合。这对于添加新的配置源和提供程序非常有用。
Environment:提供有关应用程序正在运行的 Web 托管环境的信息。
Host:一个 IHostBuilder,用于配置主机特定属性,但不进行构建。要在配置后构建,请调用 Build()。
日志记录:供应用程序组成的日志记录提供程序的集合。这对于添加新的日志记录提供程序很有用。
Services:供应用程序组成的服务集合。这对于添加用户提供的或框架提供的服务很有用。
WebHost:一个 IWebHostBuilder,用于配置服务器特定属性,但不进行构建。要在配置后构建,请调用 Build()。
要添加DbContext到 Di 容器并配置它,有很多选项,但最简单的是
builder.Services.AddDbContext<SomeDbContext>(options =>
{
options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection"));
});
Run Code Online (Sandbox Code Playgroud)
掘金包
Microsoft.EntityFrameworkCoreMicrosoft.EntityFrameworkCore.SqlServer使用UseSqlServer| 归档时间: |
|
| 查看次数: |
131841 次 |
| 最近记录: |