Skip to content
Tutorials Center
My learning

Topics

Lesson 41 of 41 ยท Projects and Practice

EF Core Practice, Troubleshooting and Interview Questions

Practice EF Core with query exercises and solutions, learn to diagnose the most common exceptions and warnings, and review typical interview questions, with runnable C# stand-ins.

You have covered mapping, relationships, loading, tracking, performance, concurrency, testing and patterns. This final lesson gives you three things: exercises to practice query thinking, a troubleshooting guide for the errors you will actually meet, and a list of interview questions with short answers.

EF Core code is read-only on this site; the exercises run as LINQ over in-memory lists, which uses the same query operators (the translation to SQL is the part EF Core adds).

Practice set 1: query exercises

Use these lists in the runner below. Try each exercise before opening the solution:

  1. List the names of customers who have at least one order over 100.
  2. For each customer, show the number of orders and the total spent, highest total first.
  3. Find the products that were never ordered.
  4. Show the best-selling product (by quantity) in each category.
  5. Page the orders: page 2 with page size 2, newest first.
C# Exercises: write your answers here

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

The code above already contains one possible answer for each exercise, so read it after you have tried. Translate each to what EF Core would run: exercise 1 becomes WHERE EXISTS (...), exercise 2 a GROUP BY (EF Core 7+ can translate this), exercise 3 NOT EXISTS, exercise 4 a window or grouped subquery (some forms need care or two steps), and exercise 5 OFFSET/FETCH (prefer keyset paging for deep pages, see query performance).

Practice set 2: spot the bug

C# Find the problem in each snippet

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Troubleshooting guide

Message or symptom Likely cause What to do
InvalidOperationException: The LINQ expression ... could not be translated A C# method or construct that has no SQL equivalent Rewrite with translatable operators, or move the unsupported part after AsEnumerable() only for the final projection
A second operation was started on this context One context used by two concurrent tasks Await each call; use a context per task (DI lifetimes)
DbUpdateException ... FOREIGN KEY constraint Inserting a child before its parent exists, or deleting a parent in use Add the parent first, check delete behavior (relationship configuration)
DbUpdateException ... Cannot insert duplicate key Unique index or key violation Check for existing row; handle the exception as a normal outcome
DbUpdateConcurrencyException Row changed or deleted since it was read Reload and retry, or merge (optimistic concurrency)
The instance of entity type X cannot be tracked because another instance with the same key is already being tracked Two objects with the same key attached to one context Use the tracked instance, detach it, or load with AsNoTracking
Navigation property is null or empty Not loaded Include, explicit loading, or a projection (loading related data)
Saved nothing, no error Entity not tracked (AsNoTracking), or property changed on a detached copy Check db.ChangeTracker.DebugView.ShortView
Slow page, many small queries N+1 Enable SQL logging, then Include or project (query performance)
Unable to create a DbContext when running dotnet ef Design-time factory missing or configuration unavailable Add an IDesignTimeDbContextFactory<T>
Cartesian explosion warning, huge result sets Several collection Includes in one query AsSplitQuery() (split queries)
Decimal precision warning No precision set HasPrecision(18, 2)

Your debugging toolkit

C#
// See the SQL
optionsBuilder.LogTo(Console.WriteLine, LogLevel.Information);   // Development only
var sql = db.Orders.Where(o => o.Total > 100).ToQueryString();   // SQL text without running it

// See what the tracker thinks
Console.WriteLine(db.ChangeTracker.DebugView.ShortView);         // quick: one line per entity
Console.WriteLine(db.ChangeTracker.DebugView.LongView);          // with property values

// See the model
Console.WriteLine(db.Model.ToDebugString());

Add EnableSensitiveDataLogging() temporarily when you need parameter values in logs, and remove it afterwards, because it can write personal data to your log files.

Interview questions with short answers

C# Flashcards: say your answer, then reveal

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with Console.ReadLine()), it gets the next line from this box.

Where to go next

  • Build the two projects on a real database with dotnet ef, and compare the generated SQL with your expectations.
  • Read your provider's documentation (SQL Server, PostgreSQL/Npgsql, SQLite, MySQL) for provider-specific features: JSON columns, temporal tables, full-text search, spatial types.
  • Revisit performance with a profiler on a real workload before optimizing.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Which tool shows the SQL for a query without executing it?

    ToQueryString() returns the SQL text EF Core would send.
  2. 2. What usually causes 'could not be translated' errors?

    EF Core translates expression trees; arbitrary C# methods have no SQL equivalent.
  3. 3. A navigation property is empty although rows exist. What is the first thing to check?

    EF Core never loads related data implicitly unless lazy loading is configured.
  4. 4. How can you see what the change tracker plans to save?

    DebugView prints each tracked entity with its state.

Summary

  • Practice query thinking with set-based LINQ, then picture the SQL EF Core produces.
  • Most EF Core problems fall into a handful of categories: translation, loading, tracking, lifetime, concurrency.
  • LogTo, ToQueryString, ChangeTracker.DebugView and Model.ToDebugString are your first debugging tools.
  • Know the vocabulary: DbContext, tracking, N+1, concurrency tokens, TPH/TPT/TPC, migrations, interceptors.

Next: back to the Entity Framework Core track page