Setting up EF Core
Install Microsoft.EntityFrameworkCore.Sqlite (or SqlServer) and Microsoft.EntityFrameworkCore.Tools via NuGet.
EF Core setup
EFSetup.cs
using Microsoft.EntityFrameworkCore;
// Entity classes
public class Blog
{
public int BlogId { get; set; }
public string Url { get; set; } = "";
public List Posts { get; set; } = [];
}
public class Post
{
public int PostId { get; set; }
public string Title { get; set; } = "";
public int BlogId { get; set; }
public Blog Blog { get; set; } = null!;
}
// DbContext
public class BlogContext : DbContext
{
public DbSet Blogs { get; set; }
public DbSet Posts { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder o)
=> o.UseSqlite("Data Source=blog.db");
} Migrations & CRUD
Run dotnet ef migrations add Initial and dotnet ef database update to create the schema. Then use the context to create, read, update, and delete.
EF CRUD
EFCRUD.cs
using var ctx = new BlogContext();
await ctx.Database.EnsureCreatedAsync();
// Create
ctx.Blogs.Add(new Blog { Url = "https://devblog.example.com" });
await ctx.SaveChangesAsync();
// Read with LINQ
var blogs = await ctx.Blogs
.Include(b => b.Posts)
.Where(b => b.Url.Contains("devblog"))
.ToListAsync();
foreach (var b in blogs)
Console.WriteLine($"{b.Url} โ {b.Posts.Count} posts");
// Update
var blog = blogs.First();
blog.Url = "https://updated.example.com";
await ctx.SaveChangesAsync();
// Delete
ctx.Blogs.Remove(blog);
await ctx.SaveChangesAsync();