Data Access in ASP.NET Core

This section covers how to work with data in your ASP.NET Core applications, focusing on common patterns, best practices, and popular libraries.

Choosing a Data Access Strategy

ASP.NET Core offers flexibility in how you interact with data. Key considerations include:

Entity Framework Core

Entity Framework Core (EF Core) is Microsoft's recommended ORM for .NET. It provides a powerful and lightweight way to work with databases.

Key Features:

Getting Started with EF Core:

1. Install EF Core packages:


dotnet add package Microsoft.EntityFrameworkCore
dotnet add package Microsoft.EntityFrameworkCore.SqlServer # Or your specific provider
dotnet add package Microsoft.EntityFrameworkCore.Tools
            

2. Define your entity classes:


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

3. Create a DbContext:


using Microsoft.EntityFrameworkCore;

public class ApplicationDbContext : DbContext
{
    public DbSet<Product> Products { get; set; }

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

4. Configure in Startup.cs (or Program.cs for .NET 6+):


// For .NET 6+ (Program.cs)
builder.Services.AddDbContext<ApplicationDbContext>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("DefaultConnection")));

// For older versions (Startup.cs)
public void ConfigureServices(IServiceCollection services)
{
    services.AddDbContext<ApplicationDbContext>(options =>
        options.UseSqlServer(Configuration.GetConnectionString("DefaultConnection")));
}
            

5. Run Migrations:


dotnet ef migrations add InitialCreate
dotnet ef database update
            

Dapper: A Micro-ORM

Dapper is a popular, high-performance micro-ORM that allows you to execute SQL queries and map the results to .NET objects with minimal overhead.

Key Features:

Getting Started with Dapper:

1. Install Dapper package:


dotnet add package Dapper
            

2. Execute queries:


using Dapper;
using System.Data.SqlClient; // Or your database provider

public async Task<IEnumerable<Product>> GetProductsAsync(string connectionString)
{
    using (var connection = new SqlConnection(connectionString))
    {
        var products = await connection.QueryAsync<Product>("SELECT * FROM Products");
        return products;
    }
}
            

Best Practices for Data Access

Tip: For complex scenarios, consider using the Unit of Work pattern with EF Core to group multiple operations into a single transaction.

Learn More: Explore the official Entity Framework Core documentation and the Dapper tutorial for in-depth guides.