Entity Framework Core Interview

Testing, Production Practices & Senior Real-World Scenarios

Entity Framework Core interview questions covering testing, production practices, resilience, batching, diagnostics, multi-tenancy and senior scenarios.

25 Questions Filter by level

Interview questions

Open a question for the full answer, code and interview guidance.

25 Results
176
SeniorAdvanced

How should EF Core code be tested?

Test business behavior at the level where it matters. Pure domain logic should usually be tested without EF Core, while persistence behavior such as mappings, constraints, transactions, query translation, and concurrency requires tests that exercise a real relational provider. Keep tests deterministic and give each test isolated data.

177
SeniorAdvanced

Should the EF Core InMemory provider be used for all database tests?

No. The InMemory provider is not a relational database and does not reproduce relational SQL translation, foreign-key constraints, transactions, collation, or provider-specific behavior. It can be useful for limited tests, but it should not be treated as a substitute for the production database engine when relational behavior is important.

178
SeniorAdvanced

When is SQLite useful for EF Core testing?

SQLite can provide fast relational tests and supports more relational behavior than the InMemory provider. It is useful when the production behavior being tested is portable across providers. However, SQLite differs from SQL Server, PostgreSQL, and other engines in types, SQL functions, concurrency, migrations, and provider-specific features, so critical provider-specific behavior should be tested against the real engine.

179
SeniorAdvanced

Why are integration tests important for EF Core applications?

Integration tests verify that the EF Core model, provider, database schema, LINQ translation, constraints, and persistence behavior work together. They can catch problems that mocked repositories or pure unit tests cannot, such as invalid SQL, missing mappings, incorrect cascade behavior, or concurrency failures. Focus integration tests on important persistence scenarios rather than duplicating every unit test.

180
SeniorAdvanced

How can database tests be isolated from each other?

Each test should start from a known state and should not depend on execution order. Isolation can be achieved with a fresh database, transaction rollback, schema reset, database respawn strategies, or separate containers/databases. The chosen technique must match the provider and test parallelism requirements.

181
SeniorAdvanced

What should be tested about EF Core migrations?

Test that migrations can create or upgrade the schema expected by the application, especially before production releases. Important upgrade paths should be exercised against realistic database states. Review generated SQL for destructive operations, locking risk, long-running data transformations, and compatibility with the deployed application version.

182
SeniorAdvanced

How should DbContext lifetime be managed in ASP.NET Core?

A DbContext is normally registered as scoped so one instance is available within a web-request scope. It represents a short-lived unit of work and should be disposed when the scope ends. DbContext is not thread-safe, so the same instance must not be used concurrently by multiple threads or parallel operations.

183
SeniorAdvanced

Why should a DbContext usually be short-lived?

A long-lived DbContext can accumulate many tracked entities, consume memory, retain stale data, and make unit-of-work boundaries unclear. A short-lived context keeps tracking manageable and makes transaction and persistence behavior easier to reason about. Background or batch workloads should create appropriately bounded contexts rather than keeping one forever.

184
SeniorAdvanced

Can one DbContext be used from multiple threads at the same time?

No. DbContext is not thread-safe and does not support concurrent operations on the same instance. Await an EF Core operation before starting another operation on that context. If work truly needs to run concurrently, use separate DbContext instances with appropriate database-level coordination.

185
SeniorAdvanced

How should EF Core be used in background services?

Background services are often singleton services, while DbContext is normally scoped. Create a scope or use IDbContextFactory for each bounded unit of background work rather than injecting a scoped DbContext directly into a singleton. Dispose each context and honor cancellation tokens so shutdown and retries are controlled.

186
SeniorAdvanced

How should cancellation tokens be used with EF Core?

Pass the request or operation CancellationToken to asynchronous EF Core methods such as ToListAsync and SaveChangesAsync. Cancellation allows abandoned HTTP requests, shutdown operations, or timed-out workflows to stop waiting for database work when the provider supports cancellation. Cancellation is not a substitute for efficient queries or appropriate command timeouts.

187
SeniorAdvanced

How should transient database failures be handled?

Transient failures are temporary errors such as brief connectivity problems or failovers. Some providers offer execution strategies that retry operations considered transient. Retries must be bounded and should not blindly repeat non-idempotent external side effects. Explicit transactions may need to be executed through the provider's execution strategy as one retriable unit.

188
SeniorAdvanced

What is an EF Core execution strategy?

An execution strategy controls how database operations are executed and can retry transient failures for providers that support retry policies. For example, SQL Server configuration can enable retry-on-failure behavior. Retries improve resilience but can increase latency during outages and require careful handling of transactions and side effects.

189
SeniorAdvanced

How should large batch operations be designed with EF Core?

Process large workloads in bounded batches rather than loading or tracking an entire dataset at once. Use set-based ExecuteUpdate or ExecuteDelete where suitable, project only needed data, and periodically create a fresh context or clear tracking when processing tracked entities in large loops. Measure transaction size, locking, log growth, and memory usage.

190
SeniorAdvanced

How can ChangeTracker.Clear help in batch processing?

ChangeTracker.Clear stops tracking all currently tracked entities efficiently. It can be useful after a completed batch when a context is intentionally reused and those entities are no longer needed. Often, creating a fresh short-lived DbContext per batch is even clearer. Do not clear tracking while pending changes still need to be saved.

191
SeniorAdvanced

How should bulk imports be approached with EF Core?

For moderate imports, AddRange with sensible batching may be sufficient. Very large imports may require provider-specific bulk-copy tools, optimized SQL, or specialized libraries because normal change tracking and individual parameterized commands can become expensive. Validate data, define transaction boundaries, measure throughput, and avoid sacrificing integrity merely for speed.

192
SeniorAdvanced

How should database deadlocks be handled in an EF Core application?

First reduce the likelihood of deadlocks by keeping transactions short, accessing shared resources in consistent order, using suitable indexes, and avoiding unnecessarily broad locks. Because deadlocks can still occur under concurrency, treat database-reported deadlock victims as potentially transient when the provider and operation support safe retry. Investigate recurring deadlocks using database diagnostics rather than only increasing retries.

193
SeniorAdvanced

How do you diagnose slow EF Core requests in production?

Separate application time from database time using tracing and metrics. Capture slow command duration, query tags, generated SQL where appropriate, execution plans, row counts, lock waits, and frequency. Check for N+1 queries, missing indexes, oversized result sets, blocking, parameter-sensitive plans, and repeated queries. Optimize only after identifying the dominant cost.

194
SeniorAdvanced

How should sensitive data logging be handled?

Sensitive data logging can include parameter values and other data in EF Core diagnostics, which is useful during controlled debugging but risky in production. Do not enable it broadly where logs may contain passwords, tokens, personal data, or confidential business information. Prefer safe structured diagnostics and tightly controlled temporary troubleshooting when detailed values are genuinely required.

195
SeniorAdvanced

How should secrets and connection strings be managed?

Do not hard-code production credentials in source code or commit them to repositories. Use environment-specific secure configuration such as secret stores, managed identity, environment variables, or deployment-platform secret facilities. Apply least privilege to database accounts and rotate credentials according to organizational policy.

196
SeniorAdvanced

How can read and write database workloads be separated?

High-scale systems may route writes to a primary database and selected read-only queries to replicas. This usually requires separate connection configuration or contexts and an understanding of replication lag. A read replica may not immediately contain a just-committed write, so workflows requiring read-your-own-write consistency should use the appropriate data source.

197
SeniorAdvanced

How should multi-tenant EF Core systems protect tenant data?

Tenant isolation must be enforced consistently for both reads and writes. Global query filters can help with reads, but authorization, tenant-key assignment, unique constraints, administrative bypasses, raw SQL, background jobs, and migrations also require tenant-aware design. Treat tenant boundaries as a security requirement and test attempts to access another tenant's data.

198
SeniorAdvanced

What EF Core issues should a senior developer look for during code review?

Look for unbounded queries, premature ToList calls, N+1 access patterns, unnecessary tracking, oversized Include graphs, missing cancellation tokens, unsafe raw SQL, incorrect context lifetime, client-controlled mass updates, weak transaction boundaries, and missing concurrency handling. Also review model constraints, indexes, delete behavior, migrations, tenant isolation, and whether generated SQL matches the intended workload.

199
SeniorAdvanced

How would you design EF Core data access for a high-traffic ASP.NET Core application?

Use short-lived scoped contexts or factories with clear units of work. Keep read queries small through projection, no-tracking, pagination, and appropriate caching outside EF Core where justified. Build indexes from measured query patterns, use optimistic concurrency for contested edits, and keep transactions short. Monitor SQL and database health continuously.

200
SeniorAdvanced

What is a strong overall EF Core strategy for production systems?

Model the database deliberately with correct keys, relationships, constraints, lengths, precision, indexes, and concurrency rules. Keep DbContext short-lived and never share it concurrently. Shape queries explicitly, retrieve only necessary data, and inspect generated SQL for important paths.