congying pan
congying pan

Reputation: 1069

Config connection string in .net core 6

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?

Upvotes: 87

Views: 153515

Answers (7)

George Piano Manikas
George Piano Manikas

Reputation: 1213

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

});

Upvotes: 120

&#198;thenwulf
&#198;thenwulf

Reputation: 220

Just add builder on your configuration code like this

builder.Configuration

Upvotes: 0

Agile Devresources
Agile Devresources

Reputation: 1

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

Upvotes: -2

Al Mubassir Muin
Al Mubassir Muin

Reputation: 438

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

Upvotes: 4

nageswararao konatham
nageswararao konatham

Reputation: 51

  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"
},

Upvotes: 5

Shadab
Shadab

Reputation: 11

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.

Upvotes: 0

TheGeneral
TheGeneral

Reputation: 81483

.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

Upvotes: 97

Related Questions