在.NET Core 6中配置连接字符串

81

我正在尝试使用SQL Server连接我的ASP.NET Core Web API应用程序(在Visual Studio 2022 Preview中使用.NET 6)。我尝试使用以下代码在Startup类中配置连接字符串,就像我以前做的那样。

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

但在.NET 6中,我注意到StartupProgram类已合并为一个类。上面的代码在.NET 6中无法使用。AddDbContext未被识别。您有关于这个更新的任何想法或文档以及如何在.NET 6中配置连接字符串的方法吗?

2
您可以在.NET Core 6中尝试以下内容: builder.Services.AddDbContext<ApplicationContext>(options=> options.UseSqlServer(builder.Configuration["ConnectionStrings:DefaultConnection"])); - Adeel Ahmed
6个回答

112

.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"));

});

96

.Net 6 简化了许多任务,并引入了WebApplicationBuilder,从而使您可以访问新的Configuration builderService Collection

var builder = WebApplication.CreateBuilder(args);

属性

  • Configuration:一个用于组合应用程序配置提供程序的集合。这对于添加新的配置源和提供程序非常有用。

  • Environment:提供有关应用程序正在运行的 Web 主机环境的信息。

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

  • Logging:一个用于组合应用程序日志记录提供程序的集合。这对于添加新的日志记录提供程序非常有用。

  • Services:一个用于组合应用程序服务的集合。这对于添加用户提供的或框架提供的服务非常有用。

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

要将 DbContext 添加到 DI 容器并配置它,有许多选项,但最简单的方法是:

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

Nugets包

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

2
@DarthScitus -- 鉴于问题的目标是NET 6,并且它不使用“startup.cs”文件,您可能需要重新考虑您的评论。如果更有经验的用户仍然决定使用旧的设置(他们可以这样做),他们已经知道应该放置在哪里,因此您的评论并不是非常有用的。 - Asons

3
  1. 安装包

    1. Microsoft.Extensions.Configuration.dll
    2. Microsoft.Extensions.Configuration.FileExtensions.dll
    3. Microsoft.Extensions.Configuration.Json.dll
  2. 在控制器中添加命名空间

    1. using Microsoft.Extensions.Configuration;
    2. using System.IO;
  3. 添加代码

Controllervar objBuilder = new ConfigurationBuilder()
          .SetBasePath(Directory.GetCurrentDirectory())
          .AddJsonFile("appSettings.json", optional: true, reloadOnChange: true);
IConfiguration conManager = objBuilder.Build();
var my = conManager.GetConnectionString("DefaultConnection");
  1. 在 appsettings.json 文件中添加以下代码:
"ConnectionStrings": {
  "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=aspnet-WebApplica71d622;Trusted_Connection=True;MultipleActiveResultSets=true"
},

我在网上花了两天时间寻找答案。这个是唯一真正有效的。谢谢! - undefined

0
首先,您应该安装以下Nugets包。
  1. Microsoft.EntityFrameworkCore
  2. Microsoft.EntityFrameworkCore.SqlServer
  3. Microsoft.EntityFrameworkCore.Tools
第二,你应该在DbContext类的构造函数中更新以下代码。
public NameOftheDBContextClass(DbContextOptions<NameOftheDBContextClass> options)
        : base(options)
    {
    }

第三步,您应该在appsettings.json中添加以下代码

"ConnectionStrings": {"YourConnectionName": "Server=YourServerName;Database=YourDataBaseName;User Id=YourDataBaseUserID;Password=YourDataBaseUserPassword;"},

第四步,你应该在Program.cs中添加以下代码。
builder.Services.AddDbContext<NameOftheDBContextClass>(options => options.UseSqlServer(builder.Configuration.GetConnectionString("YourConnectionName")));

-1

你可以在控制器中尝试这样读取..

private readonly IConfiguration _configuration;
  
public HomeController(ILogger<HomeController> logger, IConfiguration configuration)
{
    _logger = logger;
    string _configuration = configuration.GetSection("connectionStrings").GetChildren().FirstOrDefault(config => config.Key == "Title").Value;
}

注意:您可以根据上面提供的键获取值。


-2
    static string ConnectionStringSection()
    {
        var objBuilder = new ConfigurationBuilder()
      .SetBasePath(Directory.GetCurrentDirectory())
      .AddJsonFile("appSettings.json", optional: false, reloadOnChange: true);
        IConfiguration conManager = objBuilder.Build();
    
        var conn = conManager.GetConnectionString("SQLServerConnectionString");

        if (conn == null)
        {
            conn = "";
        }

        return conn.ToString();
    }

1
你好,欢迎来到Stack Overflow。你可以从这个指南中学习如何回答问题 [answer]。 - undefined
1
感谢您对Stack Overflow社区做出贡献的兴趣。这个问题已经有了相当多的答案,其中一个答案已经得到社区的广泛验证。您确定您的方法之前没有被提出过吗?如果是这样的话,能否解释一下您的方法与之前的方法有何不同,您的方法在什么情况下可能更好,并且为什么您认为之前的答案不够满意。您能否友好地编辑您的答案并提供解释? - undefined

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接