81

I'm attempting to connect to my ASP.NET Core Web API application (.NET 6 in Visual Studio 2022 Preview) with SQL Server. And I tried to use the following code to configure the connection string in the Startup class as I used to.

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

But in .NET 6, I recognize that Startup and Program classes are merged into one class. And the above code is not usable in .NET 6. AddDbContext is not recognized. So do you have any idea or documentation about this update, and how to configure connection strings in .NET 6?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
congying pan
  • 999
  • 1
  • 7
  • 10
  • 2
    You can try following in .NET Core 6: builder.Services.AddDbContext(options=> options.UseSqlServer(builder.Configuration["ConnectionStrings:DefaultConnection"])); – Adeel Ahmed Jun 29 '22 at 09:45

5 Answers5

110

Configuration.GetConnectionString(string connName) in .NET6 is under builder:

var builder = WebApplication.CreateBuilder(args);
string connString = builder.Configuration.GetConnectionString("DefaultConnection");

also AddDbContext() is under builder.Services:

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

});
Tamás Kovács
  • 263
  • 5
  • 7
George Piano Manikas
  • 1,113
  • 2
  • 6
  • 5
95

.Net 6 Simplifies a lot of a tasks and introduces WebApplicationBuilder which in turn gives you access to the new Configuration builder and Service Collection

var builder = WebApplication.CreateBuilder(args);

Properties

  • Configuration : A collection of configuration providers for the application to compose. This is useful for adding new configuration sources and providers.

  • Environment : Provides information about the web hosting environment an application is running.

  • Host : An IHostBuilder for configuring host specific properties, but not building. To build after configuration, call Build().

  • Logging : A collection of logging providers for the application to compose. This is useful for adding new logging providers.

  • Services : A collection of services for the application to compose. This is useful for adding user provided or framework provided services.

  • WebHost : An IWebHostBuilder for configuring server specific properties, but not building. To build after configuration, call Build().

To add a DbContext to the Di Container and configure it, there are many options however the most straightforward is

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

Nugets packages

  • Microsoft.EntityFrameworkCore
  • Microsoft.EntityFrameworkCore.SqlServer to use UseSqlServer
TheGeneral
  • 79,002
  • 9
  • 103
  • 141
  • 2
    @DarthScitus -- Given that the question target NET 6, and as it doesn't use a "startup.cs" file, you might want to reconsider your comment. If a more experienced user still would decide to use the older setup (which one can), they already know what goes where, again, making your comment not very useful. – Asons Oct 24 '22 at 17:54
2
  1. Install Packages

    1. Microsoft.Extensions.Configuration.dll
    2. Microsoft.Extensions.Configuration.FileExtensions.dll
    3. Microsoft.Extensions.Configuration.Json.dll
  2. Add Name Spaces in Controller

    1. using Microsoft.Extensions.Configuration;
    2. using System.IO;
  3. Add Code in

Controllervar objBuilder = new ConfigurationBuilder()
          .SetBasePath(Directory.GetCurrentDirectory())
          .AddJsonFile("appSettings.json", optional: true, reloadOnChange: true);
IConfiguration conManager = objBuilder.Build();
var my = conManager.GetConnectionString("DefaultConnection");
  1. In appsettings.json Add Code:
"ConnectionStrings": {
  "DefaultConnection": "Server=(localdb)\\mssqllocaldb;Database=aspnet-WebApplica71d622;Trusted_Connection=True;MultipleActiveResultSets=true"
},
Tasos K.
  • 7,979
  • 7
  • 39
  • 63
0

First, You Should Install Following Nugets Package

  1. Microsoft.EntityFrameworkCore
  2. Microsoft.EntityFrameworkCore.SqlServer
  3. Microsoft.EntityFrameworkCore.Tools

Second, You Should update the Following Code in DbContext Class Constructor

public NameOftheDBContextClass(DbContextOptions<NameOftheDBContextClass> options)
        : base(options)
    {
    }

Third, You Should Add the Following Code in appsettings.json

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

Fourth, You Should Add the Following Code in Program.cs

builder.Services.AddDbContext<NameOftheDBContextClass>(options => options.UseSqlServer(builder.Configuration.GetConnectionString("YourConnectionName")));
-1

You can try to read in your controller like this..

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;
}

NOTE: You can get the value based on the key provided above.

Jeremy Caney
  • 7,102
  • 69
  • 48
  • 77
Shadab
  • 1