📁 Sangam Dhakal - Portfolio v2.0 - Netscape Navigator 4.0
_
□
×

πŸ“š .NET Interview Questions

1325 questions for senior .NET engineer interviews, each with a 30-second answer, the full answer, a deep dive, the follow-ups interviewers ask next, and real-world production problems.

Phase 11 — Entity Framework Core

Entity Framework Core 10 from model to production: modelling and migrations, LINQ translation and loading strategies, change tracking, advanced mapping and concurrency, performance, and running EF Core safely in production on SQL Server.

  1. Code review: a customer dashboard API action in EF Core calls ToList() on Customers before Where, checks Count() > 0, Includes every navigation, calls FirstOrDefault against the database inside a loop over orders, and searches with Name.ToLower().Contains(term). What do you flag, in what order, and what does the rewrite look like?

    A code review of an EF Core dashboard action: client-side filtering after ToList(), Count() > 0 instead of Any(), over-eager Include, a database FirstOrDefault inside a loop (N+1), non-sargable ToLower() search, tracking and sync calls; ranked by severity with a projected rewrite.

    Mid-Level CodeReview Querying Β· πŸ”— 3 follow-ups Β· πŸ›  1 real-world
  2. How does SaveChanges work in EF Core? Walk through DetectChanges and snapshot tracking, how EF Core orders and batches the commands, the implicit transaction, and how generated keys and foreign keys are fixed up afterwards.

    Covers the SaveChanges pipeline in EF Core 10: automatic DetectChanges with snapshot tracking, dependency ordering of commands, SQL Server batching and MaxBatchSize, AutoTransactionBehavior, OUTPUT clauses for generated values, temporary keys and relationship fix-up, and what happens on failure.

    Intermediate Theory Change Tracking Β· πŸ”— 3 follow-ups
  3. How do you use the EF Core Entry API? Show how to read original and current values, check or set IsModified on a property, load a collection or reference explicitly, and use TrackGraph to set states on a disconnected graph.

    Covers the EF Core Entry API in code: EntityEntry state, CurrentValues, OriginalValues and GetDatabaseValuesAsync, PropertyEntry.IsModified and OriginalValue (including RowVersion), CollectionEntry and ReferenceEntry loading and Query(), CurrentValues.SetValues, ReloadAsync, and ChangeTracker.TrackGraph for disconnected graphs.

    Mid-Level Coding Change Tracking Β· πŸ”— 3 follow-ups Β· πŸ›  1 real-world
  4. What are the entity states in EF Core (Added, Unchanged, Modified, Deleted and Detached)? How does an entity move between them, and what does SaveChanges do with each state?

    Covers the five EF Core EntityState values, the operations that set each one, the SQL SaveChanges sends for each, and the state every entity ends in after a successful save.

    Junior Theory Change Tracking Β· πŸ”— 3 follow-ups
  5. In an ASP.NET Core API you receive an entity that was not loaded by this DbContext. When would you use Attach, Update or Add for it? Why does Update mark every column as modified, and what better approaches are there for disconnected updates?

    Covers EF Core disconnected-entity handling: how Add, Attach and Update set states across a graph based on key values, why Update writes every column, the over-posting and lost-update risks, and better patterns: load-and-apply, CurrentValues.SetValues, marking specific properties, ExecuteUpdate and concurrency tokens.

    Mid-Level Theory Change Tracking Β· πŸ”— 3 follow-ups Β· πŸ›  1 real-world
  6. Your API's update endpoint throws InvalidOperationException: "The instance of entity type 'Order' cannot be tracked because another instance with the key value '{Id: 42}' is already being tracked." How do you diagnose the cause and fix it properly?

    Covers the EF Core identity-conflict error: the identity map rule of one instance per key per context, the common causes (Attach/Update after a tracking load, duplicate objects in a graph, long-lived or singleton contexts, AutoMapper creating new instances), how to diagnose with ChangeTracker.DebugView, and the correct fixes.

    Mid-Level Debugging Change Tracking Β· πŸ”— 3 follow-ups Β· πŸ›  1 real-world
  7. Your import job tracks hundreds of thousands of entities and SaveChanges keeps getting slower. How does change tracker cost grow with the number of tracked entities, how do you keep it fast for large batches (chunking, ChangeTracker.Clear(), AutoDetectChangesEnabled), and when do you skip it with ExecuteUpdate or ExecuteDelete?

    Covers EF Core change tracker performance at scale: per-entity memory for entries and snapshots, DetectChanges cost proportional to the tracked set, the quadratic slowdown of save-per-row on one context, chunking with ChangeTracker.Clear() or a context per chunk, disabling AutoDetectChanges safely, and when to bypass the tracker with ExecuteUpdate, ExecuteDelete or SqlBulkCopy.

    Senior Theory Change Tracking Β· πŸ”— 2 follow-ups Β· πŸ›  1 real-world
  8. A queue-processing worker service using EF Core gets slower every day after a deployment, starts acting on stale data, and is eventually OOM-killed with around 500k entities tracked. Walk me through how you would diagnose it and what you would change.

    A production scenario: a BackgroundService that holds one DbContext for its lifetime, so the change tracker grows without bound, the identity map returns stale in-memory values, and the process runs out of memory; covers diagnosis with dotnet-counters, dotnet-gcdump and Application Insights, the fix with a scope or IDbContextFactory per message, and prevention.

    Senior RealWorldScenario Change Tracking Β· πŸ”— 3 follow-ups Β· πŸ›  1 real-world
  9. Code review: an update endpoint loads the entity by id, maps the whole request DTO onto it with AutoMapper, calls db.Update(entity) and SaveChanges, and returns the entity. There is no concurrency check. What do you flag, in what order, and what does the rewrite look like?

    A senior code review of an EF Core update endpoint: missing ownership check (IDOR), over-posting through whole-DTO mapping, lost updates with no RowVersion, Update() on an already-tracked entity writing every column, mapper-replaced child collections, null handling, returning entities, and the rewrite with a use-case DTO, load-check-apply-save and 409 handling.

    Senior CodeReview Change Tracking Β· πŸ”— 3 follow-ups Β· πŸ›  1 real-world
  10. How do you handle the commit-in-doubt case when a retrying execution strategy loses the connection during COMMIT?
    Intermediate Theory Advanced EF Core
  11. How do you map and call a SQL Server table-valued function from EF Core so it composes with LINQ?
    Mid-Level Theory Advanced EF Core
  12. How do you combine an EF Core tenant filter with SQL Server row-level security, and why would you want both?
    Mid-Level Theory Advanced EF Core
  13. How do transactions work in EF Core? Explain the implicit transaction around SaveChanges, when you would call BeginTransaction yourself, what savepoints do, why TransactionScope needs care, and how all of this interacts with a retrying execution strategy on Azure SQL.

    Covers EF Core transactions: the implicit SaveChanges transaction and AutoTransactionBehavior, explicit BeginTransaction and UseTransaction, automatic and manual savepoints, TransactionScope pitfalls (Serializable default, async flow, no distributed transactions on Azure SQL) and wrapping explicit transactions in the execution strategy.

    Intermediate Theory Advanced EF Core Β· πŸ”— 3 follow-ups
  14. When and how do you use raw SQL in EF Core? Compare FromSql, FromSqlRaw and SqlQuery<T>, explain ExecuteSql, show how SQL injection can still happen through string interpolation, and explain when you can compose LINQ on top of a raw query.

    Covers EF Core raw SQL APIs (FromSql/FromSqlInterpolated, FromSqlRaw, SqlQuery and SqlQueryRaw, ExecuteSql and ExecuteSqlRaw), how interpolated strings become parameters, the injection traps with FromSqlRaw and dynamic identifiers, the EF1002 analyser, and composing LINQ over composable SQL versus stored procedures.

    Mid-Level Security Advanced EF Core Β· πŸ”— 3 follow-ups Β· πŸ›  1 real-world
  15. What are EF Core interceptors? Explain command, SaveChanges and connection interceptors, how you register them and what lifetime they effectively have, and give real production uses, including what they cannot see.

    Covers EF Core interceptors: IDbCommandInterceptor, ISaveChangesInterceptor, IDbConnectionInterceptor, IMaterializationInterceptor and IQueryExpressionInterceptor; registration with AddInterceptors and DI; lifetime with pooling; suppression results; real uses (audit columns, soft delete, slow-query logging, query hints, Entra ID tokens) and the fact that ExecuteUpdate/ExecuteDelete bypass SaveChanges interceptors.

    Mid-Level Theory Advanced EF Core Β· πŸ”— 3 follow-ups Β· πŸ›  1 real-world
  16. What are global query filters in EF Core? Explain how they are applied to queries, how per-request values such as a tenant id get into them, how IgnoreQueryFilters and the named filters added in EF Core 10 work, and the pitfalls with required navigations and indexes.

    Covers EF Core global query filters: HasQueryFilter, how filters are added to every LINQ query (including Include, Find and ExecuteUpdate), parameterising them through DbContext members, IgnoreQueryFilters, EF Core 10 named filters, the required-navigation INNER JOIN pitfall (warning 10622), one filter per hierarchy root and indexing for filtered columns.

    Mid-Level Theory Advanced EF Core Β· πŸ”— 2 follow-ups Β· πŸ›  1 real-world
  17. How do you use SQL Server temporal tables with EF Core? Explain the configuration, the TemporalAsOf, TemporalAll and related query operators, using them to audit or restore data, and what they cost in storage and operations.

    Covers SQL Server system-versioned temporal tables in EF Core 6+: IsTemporal configuration, period columns as shadow properties, migrations, the TemporalAsOf/All/FromTo/Between/ContainedIn operators, restoring deleted rows, what temporal tables don't record (who changed it), history growth and retention, and alternatives such as audit tables and ledger tables.

    Mid-Level Theory Advanced EF Core Β· πŸ”— 2 follow-ups Β· πŸ›  1 real-world
  18. How do JSON columns work in EF Core 10? Explain mapping with ToJson on complex and owned types, how queries inside the JSON are translated, what the native SQL Server json type changes, how updates and indexing work, and when a JSON column is better than extra tables.

    Covers EF Core JSON mapping: ToJson on owned types (EF Core 7+) and complex types (EF Core 10), primitive collections, translation to JSON_VALUE/OPENJSON, partial updates with JSON_MODIFY, the native json data type used with Azure SQL and SQL Server 2025 (compatibility level 170), indexing through computed columns, ExecuteUpdate on JSON properties, and the design trade-offs versus normalised tables.

    Mid-Level Theory Advanced EF Core Β· πŸ”— 2 follow-ups Β· πŸ›  1 real-world
  19. How does EF Core map an inheritance hierarchy? Compare TPH, TPT and TPC: the schema each produces, the SQL for polymorphic and leaf-type queries, how keys and foreign keys work, the performance trade-offs, and which you would choose for a new system.

    Covers EF Core inheritance mapping strategies: table-per-hierarchy with a discriminator (default), table-per-type (EF Core 5+) and table-per-concrete-type (EF Core 7+); generated SQL for polymorphic and leaf queries (single table, JOINs, UNION ALL); key generation across TPC tables with sequences; foreign keys to the base type; nullability and constraint trade-offs; and how to choose.

    Senior Theory Advanced EF Core Β· πŸ”— 3 follow-ups Β· πŸ›  1 real-world
  20. Show how you implement optimistic concurrency in EF Core. Use a RowVersion or a concurrency token, explain the SQL EF Core sends, handle DbUpdateConcurrencyException with a client-wins, store-wins or merge strategy, and return the right HTTP response from an API.

    Covers EF Core optimistic concurrency: [Timestamp]/IsRowVersion on SQL Server rowversion, app-managed concurrency tokens with IsConcurrencyToken, the UPDATE ... WHERE RowVersion = @original pattern, setting OriginalValue from the client, DbUpdateConcurrencyException with GetDatabaseValuesAsync and store-wins/client-wins/merge resolution, concurrency with ExecuteUpdate, and mapping to 409 or ETag/If-Match with 412.

    Mid-Level Coding Advanced EF Core Β· πŸ”— 3 follow-ups Β· πŸ›  1 real-world

🌐 Sangam's Webring

βͺ Previous 🏠 Main Next ⏩
πŸ’¬ Chat with me