DbContext, tracking, migrations, loading, performance
Practise these as flashcards. One or two lines each; the ones you miss come back first.
Start freeDbContext manages the database connection, tracks changes to entities, and coordinates saving data to the database. It's the main class for interacting with the data model in EF Core.
I use AsNoTracking when I only need to read data and don't plan to modify or save the entities. This improves performance by skipping change tracking.
After creating a migration with 'dotnet ef migrations add', I apply it using 'dotnet ef database update', which updates the database schema to match the model.
Eager loading fetches related data as part of the initial query using the Include method. For example, context.Orders.Include(o => o.Items) loads orders and their items together.
DbContext implements the unit of work pattern by tracking all changes to entities during its lifetime and saving them in a single transaction when SaveChanges is called. This ensures consistency and atomicity for a set of operations.
The N+1 problem happens when EF Core issues one query for the main entities and then one query per related entity, leading to many database calls. I avoid it by using eager loading with Include or by restructuring queries to fetch all needed data in fewer calls.
I use FromSqlRaw or FromSqlInterpolated methods on a DbSet. For example, context.Users.FromSqlRaw("SELECT * FROM Users WHERE IsActive = 1").ToList() executes the given SQL and maps the results to entities.
A concurrency token is a property, like a RowVersion, that EF Core checks during updates to detect if another process has changed the data. If the token has changed, EF Core throws a concurrency exception, allowing me to handle conflicts.
Lazy loading automatically loads related entities when they're accessed, while explicit loading requires me to call Load() on a navigation property. Both can be useful, but lazy loading can cause hidden performance issues if not managed carefully.
I use compiled queries in EF Core, which cache the query plan and reduce overhead for repeated execution. This is especially helpful for high-traffic endpoints with similar queries.
I enable EF Core logging to inspect generated SQL, use ToQueryString() to review queries, and sometimes use database profilers or Application Insights to monitor query performance and identify bottlenecks.
Each call to SaveChanges persists the current tracked changes to the database in a transaction. However, if entities remain tracked, further changes can be saved in subsequent calls, but this can lead to unexpected behavior if not managed carefully.