![](/img/trans.png)
[英]How do I migrate this into my .NET 6 Program.cs file without using the startup class? The code is from .NET Core 2.1, also in Program.cs
[英]I am trying to register my DbContext as a service in my program.cs using .NET 6 in Visual Studio 2022, but I get an error on. GetConnectionString
我收到一條錯誤消息,提示配置不包含GetConnectionString
的定義。
這是我的Program.cs
文件:
global using Microsoft.EntityFrameworkCore;
global using LearningBlazor.Shared;
global using System.Configuration;
global using Microsoft.Extensions.Configuration;
var builder = WebApplication.CreateBuilder(args);
// Add services to the container.
builder.Services.AddControllersWithViews();
builder.Services.AddRazorPages();
builder.Services.AddDbContext<AppDbContext>(options =>
{
options.UseSqlServer(Configuration.GetConnectionString("Default"));
});
var app = builder.Build();
// Configure the HTTP request pipeline.
if (app.Environment.IsDevelopment())
{
app.UseWebAssemblyDebugging();
}
else
{
app.UseExceptionHandler("/Error");
// The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts.
app.UseHsts();
}
app.UseHttpsRedirection();
app.UseBlazorFrameworkFiles();
app.UseStaticFiles();
app.UseRouting();
app.MapRazorPages();
app.MapControllers();
app.MapFallbackToFile("index.html");
app.Run();
這就是我嘗試注冊AppDbContext
的方式:
builder.Services.AddDbContext<AppDbContext>(options =>
{
options.UseSqlServer(Configuration.GetConnectionString("Default"));
});
這是我的appsettings.json
:
{
"ConnectionStrings": {
"Default": "Server=CLARENCE\\SQLEXPRESS;Database=DDME;Trusted_Connection=True;MultipleActiveResultSets=True"
},
"Logging": {
"LogLevel": {
"Default": "Information",
"Microsoft.AspNetCore": "Warning"
}
},
"AllowedHosts": "*"
}
所以我發現我必須說builder.Congiguration
而不是像這樣的配置:
builder.Services.AddDbContext<AppDbContext>(options =>
{
//the change occurs here.
//builder.cofiguration and not just configuration
options.UseSqlServer(builder.Configuration.GetConnectionString("Default"));
});
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.