Skip to content

Entity Framework Core Basics with Examples: DbContext, Migrations, LINQ Queries and Relationships

Gulab Chand Tejwani

Gulab Chand Tejwani

PMP · PL-300 · Microsoft Certified Trainer

· 12 min read

Entity Framework CoreEF Core.NETC#SQL ServerASP.NET Core
Entity Framework Core Basics with Examples: DbContext, Migrations, LINQ Queries and Relationships

Entity Framework Core (EF Core) is Microsoft's object-relational mapper for .NET. You describe your data as C# classes, create a DbContext that exposes them as DbSet properties, and EF Core translates your LINQ queries into SQL and tracks changes so SaveChangesAsync() can write them back. The basic workflow is: define entities, register the context, create the database with dotnet ef migrations add and dotnet ef database update, then query and save through the context. The current version is EF Core 10, released with .NET 10 in November 2025.

I'm Gulab Chand Tejwani, a Microsoft Certified Trainer at TechNet Consultancy in Anand. EF Core sits underneath nearly every .NET business application we build for clients, and it's the topic where I see learners lose the most time to small mistakes. This guide uses one example from start to finish: a training institute with courses and enrolments.

Five-step EF Core workflow: entities, DbContext, migrations, query, save
The whole guide in one picture. Each step below matches one box.

What do you need?

  • The .NET 10 SDK
  • A database. SQL Server LocalDB or Express on Windows, or SQLite anywhere. The examples use SQL Server; switching to SQLite is one package and one line.
  • The EF Core command-line tools:
dotnet tool install --global dotnet-ef

In your project, add the provider and design packages:

dotnet add package Microsoft.EntityFrameworkCore.SqlServer
dotnet add package Microsoft.EntityFrameworkCore.Design

Step 1: Define your entities

Entities are plain classes. EF Core works out tables, columns and keys by convention: a property called Id or CourseId becomes the primary key, and a property like CourseId on another class becomes a foreign key.

public class Course
{
    public int Id { get; set; }
    public string Title { get; set; } = "";
    public int DurationHours { get; set; }
    public decimal Fee { get; set; }

    public List<Enrolment> Enrolments { get; set; } = [];
}

public class Student
{
    public int Id { get; set; }
    public string Name { get; set; } = "";
    public string Email { get; set; } = "";

    public List<Enrolment> Enrolments { get; set; } = [];
}

public class Enrolment
{
    public int Id { get; set; }
    public int CourseId { get; set; }
    public Course Course { get; set; } = null!;
    public int StudentId { get; set; }
    public Student Student { get; set; } = null!;
    public DateOnly EnrolledOn { get; set; }
    public bool Completed { get; set; }
}

Enrolment links students and courses, giving you two one-to-many relationships. I prefer an explicit join entity like this over a hidden many-to-many, because real systems almost always need extra columns on the link, such as the enrolment date.

Step 2: Create the DbContext

using Microsoft.EntityFrameworkCore;

public class TrainingDb(DbContextOptions<TrainingDb> options) : DbContext(options)
{
    public DbSet<Course> Courses => Set<Course>();
    public DbSet<Student> Students => Set<Student>();
    public DbSet<Enrolment> Enrolments => Set<Enrolment>();

    protected override void OnModelCreating(ModelBuilder model)
    {
        model.Entity<Course>(e =>
        {
            e.Property(c => c.Title).HasMaxLength(120).IsRequired();
            e.Property(c => c.Fee).HasPrecision(10, 2);
        });

        model.Entity<Student>()
            .HasIndex(s => s.Email)
            .IsUnique();
    }
}

OnModelCreating is where you configure what conventions can't guess: string lengths, decimal precision, indexes, unique constraints. Without HasMaxLength, SQL Server strings become nvarchar(max), which you rarely want.

Register it in Program.cs of an ASP.NET Core app:

builder.Services.AddDbContext<TrainingDb>(options =>
    options.UseSqlServer(builder.Configuration.GetConnectionString("Training")));

And put the connection string in appsettings.json (or user secrets for anything with a password):

{
  "ConnectionStrings": {
    "Training": "Server=(localdb)\\mssqllocaldb;Database=Training;Trusted_Connection=True;"
  }
}

AddDbContext registers the context as scoped, so each web request gets its own instance. Don't make a DbContext a singleton; it isn't thread-safe.

Step 3: Create the database with migrations

Migrations are versioned C# files describing schema changes.

dotnet ef migrations add InitialCreate
dotnet ef database update

The first command generates a Migrations folder. Open it and read the Up method: that's what will run against your database. The second command applies it. When you change an entity later, say by adding Mode to Course, run migrations add AddCourseMode and database update again.

For production, many teams generate a SQL script with dotnet ef migrations script --idempotent and have it reviewed, rather than running database update against a live server. The EF Core migrations docs explain the options.

Step 4: Insert and update data

var blazor = new Course { Title = "Blazor Training", DurationHours = 40, Fee = 0m };
db.Courses.Add(blazor);
await db.SaveChangesAsync();   // INSERT; blazor.Id is now set

blazor.DurationHours = 42;
await db.SaveChangesAsync();   // UPDATE, only the changed column

The context tracks entities it loaded or added. When you call SaveChangesAsync, it compares current values with the originals and sends only the necessary SQL, inside a transaction.

For bulk changes, don't load rows just to modify them. ExecuteUpdateAsync and ExecuteDeleteAsync run a single SQL statement:

await db.Enrolments
    .Where(e => e.EnrolledOn < new DateOnly(2025, 1, 1) && !e.Completed)
    .ExecuteDeleteAsync();

Step 5: Query with LINQ

var longCourses = await db.Courses
    .AsNoTracking()
    .Where(c => c.DurationHours >= 30)
    .OrderBy(c => c.Title)
    .Select(c => new { c.Id, c.Title, c.DurationHours })
    .ToListAsync();

Three habits in that query:

  • AsNoTracking() for read-only data. EF Core skips change tracking, which saves memory and time.
  • Select a projection instead of loading full entities. You fetch only the columns you show.
  • ToListAsync() at the end. Nothing hits the database until you enumerate. Everything before it builds the SQL.

Want to see the SQL? Call .ToQueryString() on the query, or turn on logging with options.LogTo(Console.WriteLine) while developing. I ask every learner to do this at least once for each new kind of query.

Here are the LINQ methods you'll use daily and the SQL they roughly become. Seeing them side by side makes the generated SQL much less mysterious.

LINQRoughly becomesNote
Where(c => c.Fee > 0)WHERE Fee > 0Runs in the database if before ToList
OrderBy(c => c.Title)ORDER BY TitleAdd ThenBy for a second key
Select(c => new { c.Title })SELECT TitleFetch only what you show
Skip(20).Take(10)OFFSET 20 ROWS FETCH NEXT 10Always with OrderBy for stable pages
Any(c => c.Fee == 0)EXISTS (...)Cheaper than Count() > 0
GroupBy(e => e.CourseId).Select(...Count())GROUP BY CourseId with COUNT(*)Aggregate in SQL, not in memory
Everyday LINQ in EF Core and the SQL it produces

A paged list endpoint brings several of these together:

app.MapGet("/courses", async (TrainingDb db, int page = 1, int size = 10) =>
{
    size = Math.Clamp(size, 1, 50);
    var query = db.Courses.AsNoTracking().OrderBy(c => c.Title);

    var total = await query.CountAsync();
    var items = await query
        .Skip((page - 1) * size)
        .Take(size)
        .Select(c => new { c.Id, c.Title, c.DurationHours })
        .ToListAsync();

    return Results.Ok(new { total, page, size, items });
});

Math.Clamp stops a caller asking for a million rows in one request. Small guards like that matter more than clever queries.

Step 6: Load related data

var course = await db.Courses
    .Include(c => c.Enrolments)
        .ThenInclude(e => e.Student)
    .FirstOrDefaultAsync(c => c.Id == 1);

Include tells EF Core to fetch the related rows in the same query. Without it, course.Enrolments is empty, since EF Core doesn't lazy-load by default.

Often a projection is better than Include, because it pulls only what you need:

var summary = await db.Courses
    .Select(c => new
    {
        c.Title,
        Enrolled = c.Enrolments.Count,
        Completed = c.Enrolments.Count(e => e.Completed)
    })
    .ToListAsync();

EF Core turns that into a single SQL query with grouped counts.

What's new in EF Core 10?

Highlights from Microsoft's What's New in EF Core 10:

  • LeftJoin and RightJoin LINQ operators, replacing the awkward GroupJoin/DefaultIfEmpty pattern
  • Named query filters, so you can have several global filters (soft delete, multi-tenant) and turn off one at a time
  • Complex types improvements, including mapping to JSON columns and struct support
  • Vector search support for SQL Server 2025 and Azure SQL Database, useful for AI features such as RAG chatbots
  • Simpler ExecuteUpdateAsync that accepts a regular lambda, so conditional updates are easier to write

None of these change the basics above. Learn the basics first.

EF Core 10 highlights grouped into queries, modelling, updates and AI
EF Core 10 highlights, from Microsoft's What's New page. None of them replaces the basics.

Here's how the new LeftJoin reads compared with the old pattern, for "every course with its enrolments, including courses nobody has joined yet":

// EF Core 10
var rows = await db.Courses
    .LeftJoin(db.Enrolments,
        c => c.Id,
        e => e.CourseId,
        (c, e) => new { c.Title, EnrolledOn = e == null ? (DateOnly?)null : e.EnrolledOn })
    .ToListAsync();

Before EF Core 10 you wrote the same thing with GroupJoin, SelectMany and DefaultIfEmpty, which worked but confused almost everyone who read it.

What mistakes cause slow EF Core apps?

  • N+1 queries. Looping over courses and touching course.Enrolments inside the loop, with lazy loading switched on, runs one query per course. Use Include or a projection.
  • Loading everything, then filtering in memory. db.Courses.ToList().Where(...) downloads the whole table. Keep Where before ToListAsync.
  • Tracking large read-only lists. Use AsNoTracking.
  • Missing indexes. EF Core creates indexes for foreign keys, but not for the columns you search on. Add them in OnModelCreating.
  • Long-lived contexts. One context per request or unit of work. In Blazor Server, use IDbContextFactory and create a short-lived context per operation.
Slow EF Core habits next to their fast replacements
Five habits that cover most of the EF Core performance problems I see in learners' and clients' code.

The N+1 problem is worth seeing in code, because it hides so well:

// N+1: one query for courses, then one more per course (with lazy loading on)
foreach (var c in await db.Courses.ToListAsync())
    Console.WriteLine($"{c.Title}: {c.Enrolments.Count}");

// One query: let the database count
var counts = await db.Courses
    .Select(c => new { c.Title, Count = c.Enrolments.Count })
    .ToListAsync();

With 200 courses, the first version sends 201 queries. The second sends one. Turn on LogTo(Console.WriteLine) and you'll see the difference immediately.

How do you test code that uses EF Core?

You have three options, and Microsoft's testing guidance is fairly direct about them:

OptionGood forWatch out for
Real database (e.g. SQL Server in a container)Integration tests that must match productionSlower; needs setup and cleanup
SQLite in-memoryFast tests with a real relational engineSQL differences from SQL Server
EF Core in-memory providerVery simple cases onlyNot relational; Microsoft discourages it for testing
Ways to test EF Core code

For learners I suggest SQLite in-memory for unit-level tests and one or two integration tests against the real database engine you deploy to.

Should you still learn SQL?

Yes. EF Core writes SQL for you; it doesn't stop you needing to understand it. When a page is slow, you'll read the generated SQL and the execution plan. Our SQL training and the post on why SQL matters are good companions to this guide.

Where does EF Core fit in a .NET career?

It's the data layer of the stack I describe in the .NET developer roadmap 2026: C#, then ASP.NET Core, then EF Core, then Blazor. Plug this TrainingDb into the endpoints from the ASP.NET Core Web API tutorial and you have a real back end.

Our .NET Blazor training covers state, data access and API integration in C#, and the SQL training builds the database skills underneath. Both run live online or in our classroom in Anand. If you need a .NET application built on a solid data layer, our software and web development team does that work for clients.

FAQ

What is the difference between EF Core and Entity Framework 6?

Entity Framework 6 is the older framework for .NET Framework, now in maintenance. EF Core is the modern, cross-platform rewrite for current .NET and gets all new features. Start new projects with EF Core.

Is EF Core slower than writing SQL by hand?

For typical business queries the difference is small, especially with AsNoTracking and projections. For a few heavy reports you can run raw SQL with FromSql or use Dapper alongside EF Core in the same project.

Code-first or database-first?

Code-first with migrations suits new applications. If the database already exists, scaffold the model with dotnet ef dbcontext scaffold and work from there. Both are fully supported.

Which databases does EF Core support?

Microsoft maintains providers for SQL Server, Azure SQL, SQLite, Azure Cosmos DB and an in-memory provider for tests. Community providers cover PostgreSQL (Npgsql), MySQL and others.

Do I need to learn LINQ before EF Core?

Basic LINQ helps a lot: Where, Select, OrderBy, Any, Count and FirstOrDefault. Learn it on in-memory lists first, then the same methods feel natural with EF Core.

Choose optional cookies

We use necessary cookies for account security. With your permission, we also use analytics and advertising cookies on marketing pages. See our Privacy Policy.