This sequence diagram visualizes how Entity Framework processes a query, step-by-step.
The key steps are outlined below the diagram for clarity.
Click on the image for a larger view in a new window.
Entity Framework Query Flow Explained
Here’s what happens when you run a query with Entity Framework:
1️⃣ LINQ Query Starts:
Everything begins when your app initiates a LINQ query (like dbContext.Players.Where(...)
).
2️⃣ Check for Compiled Query Cache:
EF checks if this exact query has been compiled before. If it’s cached, EF skips re-compiling, saving time.
If not cached? EF compiles the query, converting it from LINQ to SQL.
3️⃣ SQL Execution:
EF sends the SQL query to the database. This is the part where the database engine kicks in.
4️⃣ Database Processes the Query:
The database does its job—filtering, joining, aggregating—and returns the result set.
5️⃣ Handling Errors (if any):
If there’s a SQL error (like a timeout, syntax issue, or connection problem), EF throws an exception.
6️⃣ Return Query Results:
Assuming no errors, the raw data comes back to EF. But it’s just rows of data at this point, not actual objects.
7️⃣ Mapping Data to Entities:
EF maps the raw database results to your .NET classes (like Player
objects). This is called hydration.
8️⃣ Instantiating Entities:
EF creates actual instances of your entities (new Player()
), filling them with the data from the database.
9️⃣ Change Tracking (or Not):
EF checks if change tracking is enabled:
- With tracking (default): EF attaches these entities to the change tracker, monitoring for updates.
- Without tracking (
AsNoTracking()
): EF skips this step, which improves performance for read-only queries.
🔄 Return to Your App:
EF returns the collection of entities back to your app. This is what your LINQ query gives you.
♻️ Clean Up:
Finally, the DbContext
is disposed of, releasing resources. This often happens automatically, especially if you’re using dependency injection.