How do I connect ASP.NET Core 5 or 6 Applications with Microsoft SQL Server?
How do I connect ASP.NET Core 5 or 6 Applications with Microsoft SQL Server?
We can connect SQL Server in ASP.NET Core applications in multiple ways.
Use entity framework to connect SQL Server in ASP.NET Core applications
Refer to this tutorial:
Build ASP.NET Core Web API with CRUD Operations Using Entity Framework Core
.Net 6 Simplifies a lot of 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"));
});
Required Nugets packages:
Microsoft.EntityFrameworkCore
Microsoft.EntityFrameworkCore.SqlServer
to use UseSqlServer
Reference: WebApplicationBuilder Class Thanks to Microsoft.
Not a builder, but an IHostBuilder for configuring host-specific properties. Call Build to construct following configuration. An assemblage of logging providers that the application is designed to construct. This feature facilitates the addition of additional recording providers.