Entity Framework Core – Data Access Tutorial

Entity Framework Core (EF Core) is a modern, cross‑platform object‑relational mapper (ORM) that enables .NET developers to work with a database using .NET objects.

Prerequisites

1. Create a new project

dotnet new console -n EfCoreDemo
cd EfCoreDemo

2. Add EF Core packages

dotnet add package Microsoft.EntityFrameworkCore
dotnet add package Microsoft.EntityFrameworkCore.Sqlite
dotnet add package Microsoft.EntityFrameworkCore.Tools

3. Define your model

using Microsoft.EntityFrameworkCore;

public class BloggingContext : DbContext
{
    public DbSet<Blog> Blogs { get; set; }
    public DbSet<Post> Posts { get; set; }

    protected override void OnConfiguring(DbContextOptionsBuilder options)
        => options.UseSqlite("Data Source=blogging.db");
}

public class Blog
{
    public int BlogId { get; set; }
    public string? Url { get; set; }
    public List<Post> Posts { get; set; } = new();
}

public class Post
{
    public int PostId { get; set; }
    public string? Title { get; set; }
    public string? Content { get; set; }
    public int BlogId { get; set; }
    public Blog? Blog { get; set; }
}

4. Create and apply a migration

dotnet ef migrations add InitialCreate
dotnet ef database update

5. Perform basic CRUD operations

using var db = new BloggingContext();

// CREATE
var blog = new Blog { Url = "https://example.com" };
db.Blogs.Add(blog);
db.SaveChanges();

// READ
var blogs = db.Blogs
    .OrderBy(b => b.BlogId)
    .ToList();

Console.WriteLine($"Blogs count: {blogs.Count}");

// UPDATE
var first = db.Blogs.First();
first.Url = "https://contoso.com";
db.SaveChanges();

// DELETE
var toDelete = db.Blogs.FirstOrDefault(b => b.BlogId == 1);
if (toDelete != null)
{
    db.Blogs.Remove(toDelete);
    db.SaveChanges();
}

Next steps

Explore more advanced scenarios such as querying with LINQ, managing migrations, and optimizing performance.

Resources