Skip to content

Instantly share code, notes, and snippets.

@PureKrome
Created April 21, 2026 02:36
Show Gist options
  • Select an option

  • Save PureKrome/d7489ccdc298249a55077797f68d3acf to your computer and use it in GitHub Desktop.

Select an option

Save PureKrome/d7489ccdc298249a55077797f68d3acf to your computer and use it in GitHub Desktop.
EF Core + SQLite Quickstart

EF Core + SQLite Quickstart

Models

// Models/User.cs
namespace MyApp.Api.Models;

public class User
{
    public int Id { get; init; }
    public required string Name { get; init; }
    public DateTime CreatedAt { get; init; } = DateTime.UtcNow;
}
// Models/Post.cs
namespace MyApp.Api.Models;

public class Post
{
    public int Id { get; init; }
    public required string Title { get; init; }
    public required string Body { get; init; }
    public int UserId { get; init; }
    public User User { get; init; } = null!;
    public DateTime CreatedAt { get; init; } = DateTime.UtcNow;
}

DbContext

// Infrastructure/Persistence/AppDbContext.cs
namespace MyApp.Api.Infrastructure.Persistence;

public class AppDbContext(DbContextOptions<AppDbContext> options) : DbContext(options)
{
    public DbSet<User> Users => Set<User>();
    public DbSet<Post> Posts => Set<Post>();

    protected override void OnModelCreating(ModelBuilder modelBuilder)
    {
        modelBuilder.Entity<User>(entity =>
        {
            entity.HasKey(e => e.Id);
            entity.Property(e => e.Name).IsRequired();
        });

        modelBuilder.Entity<Post>(entity =>
        {
            entity.HasKey(e => e.Id);
            entity.Property(e => e.Title).IsRequired();
            entity.Property(e => e.Body).IsRequired();
            entity.HasOne(e => e.User)
                  .WithMany()
                  .HasForeignKey(e => e.UserId);
        });
    }
}

Wiring Up

appsettings.json

{
  "ConnectionStrings": {
    "DefaultConnection": "Data Source=myapp.db"
  }
}

Program.cs

using MyApp.Api.Infrastructure.Persistence;
using Microsoft.EntityFrameworkCore;

builder.Services.AddDbContext<AppDbContext>(options =>
    options.UseSqlite(builder.Configuration.GetConnectionString("DefaultConnection")));

NuGet packages

dotnet add package Microsoft.EntityFrameworkCore.Sqlite
dotnet add package Microsoft.EntityFrameworkCore.Design

Migrations

# create the initial migration
dotnet ef migrations add InitialCreate

# apply to database (creates the .db file if it doesn't exist)
dotnet ef database update

If dotnet ef is not found, install the tool globally:

dotnet tool install --global dotnet-ef

Subsequent schema changes follow the same pattern - add a migration with a descriptive name, then update:

dotnet ef migrations add AddPostTags
dotnet ef database update
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment