// 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;
}// 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);
});
}
}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# create the initial migration
dotnet ef migrations add InitialCreate
# apply to database (creates the .db file if it doesn't exist)
dotnet ef database updateIf
dotnet efis 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