簡體   English   中英

我正在嘗試在 Visual Studio 2022 中使用 .NET 6 將我的 DbContext 注冊為我的 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM