ASP.NET Core Data Access

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

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}");
}