Connecting to a database in ASP.NET Core is essential for many applications that require data storage and retrieval. The most common way to interact with a database in ASP.NET Core is through Entity Framework Core (EF Core), which is an Object-Relational Mapper (ORM). This guide will walk you through the steps to connect to a database using EF Core in an ASP.NET Core application.

Step 1: Install Required Packages

To use Entity Framework Core, you need to install the necessary NuGet packages. You can do this using the .NET CLI or through the NuGet Package Manager in Visual Studio. For example, to install EF Core with SQL Server support, run the following commands in your project directory:

        
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Microsoft.EntityFrameworkCore.Tools

Step 2: Create a Database Context

The database context is a class that derives from DbContext and represents a session with the database. It is responsible for querying and saving data. Below is an example of a simple database context for a product management application.

        
using Microsoft.EntityFrameworkCore;

public class ApplicationDbContext : DbContext
{
public ApplicationDbContext(DbContextOptions<ApplicationDbContext> options)
: base(options)
{
}

public DbSet<Product> Products { get; set; } // DbSet for Product entity
}

public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public decimal Price { get; set; }
}

Explanation of the Database Context Code

In the ApplicationDbContext class:

  • Constructor: The constructor accepts DbContextOptions which are used to configure the context, including the connection string.
  • DbSet: The DbSet<Product> property represents the collection of Product entities in the database. EF Core uses this property to perform CRUD operations on the Product table.

Step 3: Configure the Database Connection

You need to configure the database connection in the Startup class. This is where you specify the connection string and register the database context with the dependency injection container.

        
using Microsoft.EntityFrameworkCore;

public class Startup
{
public void ConfigureServices(IServiceCollection services)
{
// Configure the database context with SQL Server
services.AddDbContext<ApplicationDbContext>(options =>
options.UseSqlServer("YourConnectionStringHere"));

services.AddControllers(); // Add services for controllers
}

public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
else
{
app.UseExceptionHandler("/Home/Error");
app.UseHsts();
}

app.UseHttpsRedirection();
app.UseRouting();
app.UseAuthorization();

app.UseEndpoints(endpoints =>
{
endpoints.MapControllers(); // Map attribute-routed controllers
});
}
}

Explanation of the Startup Configuration

In the Startup class:

  • ConfigureServices Method: The AddDbContext method registers the ApplicationDbContext with the dependency injection container. The UseSqlServer method specifies the connection string to the SQL Server database.
  • Connection String: Replace YourConnectionStringHere with your actual database connection string, which typically includes the server name, database name, and authentication details.

Step 4: Applying Migrations

After setting up the database context, you need to create and apply migrations to create the database schema. You can do this using the .NET CLI:

        
dotnet ef migrations add InitialCreate
dotnet ef database update

Explanation of Migrations

Migrations are a way to keep your database schema in sync with your application’s data model. The dotnet ef migrations add InitialCreate command creates a migration based on the current model, and dotnet ef database update applies the migration to the database, creating the necessary tables.

Step 5: Using the Database Context

Now that you have set up the database context and applied migrations, you can use the context to perform CRUD operations. Below is an example of a simple controller that uses the ApplicationDbContext to manage products.

        
using Microsoft.AspNetCore.Mvc;

[Route("api/[controller]")]
[ApiController]
public class ProductsController : ControllerBase
{
private readonly ApplicationDbContext _context;

public ProductsController(ApplicationDbContext context)
{
_context = context;
}

[HttpGet]
public async Task<ActionResult<IEnumerable<Product>>> GetProducts()
{
return await _context.Products.ToListAsync();
}

[HttpPost]
public async Task<ActionResult<Product>> PostProduct(Product product)
{
_context.Products.Add(product);
await _context.SaveChangesAsync();
return CreatedAtAction(nameof(GetProducts), new { id = product.Id }, product);
}
}

Conclusion

Connecting to a database in ASP.NET Core using Entity Framework Core is straightforward. By following the steps outlined above, you can set up a database context, configure your application, and perform CRUD operations on your data. This approach allows you to leverage the power of EF Core to manage your database interactions efficiently.