Day 16: Entity Framework Core Setup
Welcome to Day 16. So far, every time we restart our server, our List<string> resets. It’s time to connect a real database.
Writing raw SQL queries works, but it’s tedious and prone to security vulnerabilities (SQL Injection). Instead, modern .NET uses an ORM (Object-Relational Mapper) called Entity Framework Core (EF Core).
EF Core allows you to map your C# Classes directly to Database Tables.
Step 1: Install the Packages
If you are using PostgreSQL, SQL Server, or SQLite, you need the specific provider package. For local development, SQLite is amazing because it saves the database to a local file.
Run this in your terminal:
dotnet add package Microsoft.EntityFrameworkCore.Sqlite
dotnet add package Microsoft.EntityFrameworkCore.Tools
Step 2: Create your Entity (Model)
This is a standard C# class. EF Core will eventually turn this into a table.
public class Book
{
// EF Core recognizes 'Id' as the Primary Key automatically!
public int Id { get; set; }
public string Title { get; set; } = string.Empty;
public string Author { get; set; } = string.Empty;
public decimal Price { get; set; }
}
Step 3: Create the DbContext
The DbContext is the bridge between your C# code and the database. Think of it as the representative of your entire database.
using Microsoft.EntityFrameworkCore;
public class AppDbContext : DbContext
{
// Passing configuration down to the base EF Core DbContext
public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { }
// Every DbSet represents a Table in the database!
public DbSet<Book> Books { get; set; }
}
Step 4: Register it in Program.cs
Remember Dependency Injection? We need to tell the builder how to create our AppDbContext and what connection string to use.
// Program.cs
var builder = WebApplication.CreateBuilder(args);
// Register the DbContext!
builder.Services.AddDbContext<AppDbContext>(options =>
options.UseSqlite("Data Source=library.db") // This will create a local file!
);
var app = builder.Build();
Right now, if you try to query this database, it will crash because the library.db file and the Books table don’t exist yet!
Tomorrow we will learn how to generate the physical database schema from our C# code using Migrations.
Challenge for Day 16
Set up the boilerplate. Create a .NET 8 Web API project. Install the SQLite EF packages. Create a Movie entity, an AppDbContext, and register the connection string in Program.cs!
Tomorrow: EF Core Migrations.