Introduction
Data access is a cornerstone of any web application. In ASP.NET Core you have a variety of options to interact with databases, ranging from raw ADO.NET to powerful ORMs like Entity Framework Core.
Choosing the Right Approach
- Entity Framework Core – High-level, productivity‑focused ORM.
- Dapper – Lightweight micro‑ORM for performance‑critical scenarios.
- Ado.NET – Full control with raw SQL commands.
- Cosmos DB SDK – For NoSQL workloads.
Getting Started with EF Core
Install the package:
dotnet add package Microsoft.EntityFrameworkCore.SqlServer
Create a DbContext:
using Microsoft.EntityFrameworkCore;
public class AppDbContext : DbContext
{
public DbSet<Product> Products { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder options)
{
options.UseSqlServer("Server=.;Database=MyApp;Trusted_Connection=True;");
}
}
Define an entity:
public class Product
{
public int Id { get; set; }
public string Name { get; set; } = string.Empty;
public decimal Price { get; set; }
}
Using Dapper
Install the Dapper package:
dotnet add package Dapper
Example query:
using System.Data.SqlClient;
using Dapper;
using var connection = new SqlConnection("Server=.;Database=MyApp;Trusted_Connection=True;");
var products = await connection.QueryAsync<Product>("SELECT * FROM Products");
foreach (var p in products)
{
Console.WriteLine($"{p.Id}: {p.Name} – ${p.Price}");
}