Introduction
Data access is a core part of any .NET application. This guide explores the primary mechanisms available when building .NET Core applications, helping you choose the right tool for your scenario.
Data Access Options
- Entity Framework Core (EF Core) – A full‑featured ORM with LINQ support.
- ADO.NET – Low‑level, high‑performance data access using
DbConnection
andDbCommand
. - Dapper – A lightweight micro‑ORM that extends ADO.NET with object mapping.
Entity Framework Core
EF Core provides a high‑level abstraction for database interactions, enabling developers to work with strongly typed objects and LINQ queries.
using var context = new BloggingContext();
var posts = await context.Posts
.Where(p => p.Published)
.OrderByDescending(p => p.PublishedDate)
.ToListAsync();
Key features:
- Change tracking
- Migrations for schema evolution
- Query caching & compiled queries
ADO.NET
When ultimate control and performance are required, ADO.NET gives you direct access to the database driver.
using var connection = new SqlConnection(connectionString);
await connection.OpenAsync();
using var command = new SqlCommand("SELECT Title FROM Posts WHERE Published = @p", connection);
command.Parameters.AddWithValue("@p", true);
using var reader = await command.ExecuteReaderAsync();
while (await reader.ReadAsync())
{
Console.WriteLine(reader.GetString(0));
}
Consider ADO.NET for:
- Batch operations
- Complex stored procedures
- Scenarios where EF Core overhead is too high
Dapper
Dapper offers a sweet spot between raw ADO.NET and a full ORM, delivering fast object mapping with minimal configuration.
using var connection = new SqlConnection(connectionString);
var posts = await connection.QueryAsync<Post>(
"SELECT * FROM Posts WHERE Published = @Published",
new { Published = true });
Typical use‑cases:
- Read‑heavy APIs
- Micro‑services where payload size matters
- Projects that already use ADO.NET extensively
Choosing the Right Approach
Scenario | Recommended |
---|---|
Simple CRUD with relational model | EF Core |
High‑throughput read‑only API | Dapper |
Complex stored procedures & bulk inserts | ADO.NET |