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?
To read the connection string into your code, use the ConfigurationManager class. string connStr = ConfigurationManager. ConnectionStrings["myConnectionString"].
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"));
});
.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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With