50 Entity Framework Core Interview Questions Every Senior .NET Developer Should Know
Master EF Core with real interview questions covering DbContext, Tracking, LINQ, Performance, Migrations, Transactions and Architecture.
Table of Contents
- 1. What is Entity Framework Core?
- 2. What are the advantages of EF Core?
- 3. What is DbContext?
- 4. What is DbSet<T>?
- 5. How does EF Core communicate with a database?
- 6. What is Change Tracking?
- 7. What is the difference between EF6 and EF Core?
- 8. What is Code First?
- 9. What is Database First?
- 10. What are Migrations?
- 11. What is EntityState?
- 12. What is ChangeTracker?
- 13. What is AsNoTracking()?
- 14. When should AsNoTracking be used?
- 15. What is AutoDetectChanges?
- 16. What is eager loading?
- 17. What is lazy loading?
- 18. What is explicit loading?
- 19. What is Include()?
- 20. What is ThenInclude()?
- 21. What are navigation properties?
- 22. What is the N+1 query problem?
- 23. How can N+1 queries be avoided?
- 24. What is projection?
- 25. Why use Select() instead of Include()?
- 26. What are compiled queries?
- 27. What is query compilation?
- 28. What is batching?
- 29. What is connection pooling?
- 30. How do you optimize EF Core performance?
- 31. What is ExecuteUpdate()?
- 32. What is ExecuteDelete()?
- 33. What is a transaction?
- 34. What is optimistic concurrency?
- 35. What is RowVersion?
- 36. What is a Repository Pattern?
- 37. Should EF Core use Repository Pattern?
- 38. What is Unit of Work?
- 39. Is DbContext a Unit of Work?
- 40. How do you implement transactions in EF Core?
- 41. What is query splitting?
- 42. What is a cartesian explosion?
- 43. How does EF Core support Dependency Injection?
- 44. What is a shadow property?
- 45. What is value conversion?
- 46. How do you seed data in EF Core?
- 47. How do you handle large datasets?
- 48. How do you debug generated SQL?
- 49. How would you use EF Core in a microservice architecture?
- 50. What are the most common EF Core mistakes developers make?
🎁 Free .NET Interview PDF
Download 150 Real .NET Interview Questions
Includes C#, ASP.NET Core, Entity Framework, Async/Await, LINQ, System Design, Caching, Microservices and more.
No spam. Unsubscribe anytime.
1. What is Entity Framework Core?
Entity Framework Core (EF Core) is Microsoft's modern Object Relational Mapper (ORM) for .NET applications. It allows developers to work with databases using strongly typed C# objects rather than writing large amounts of SQL manually. EF Core translates LINQ queries into SQL statements and maps database records to .NET entities. EF Core supports SQL Server, PostgreSQL, MySQL, SQLite, Cosmos DB and many other providers. It has become the default data access technology in ASP.NET Core applications and is frequently discussed in modern .NET interviews.
2. What are the advantages of EF Core?
EF Core improves developer productivity by reducing boilerplate data access code. Developers can write LINQ queries instead of manually building SQL strings. EF Core also provides change tracking, migrations, relationship management, transactions, caching optimizations, and database abstraction. Because of its tight integration with ASP.NET Core and Dependency Injection, EF Core is widely used in enterprise systems and cloud-native applications.
3. What is DbContext?
DbContext is the primary class responsible for interacting with the database in Entity Framework Core. It acts as a Unit of Work and manages entity tracking, query execution, database updates, and transactions. Through DbContext, developers can retrieve data, insert records, update entities, and remove records. When SaveChanges is called, EF Core generates the required SQL statements and synchronizes changes with the database.
4. What is DbSet<T>?
DbSet<T> represents a collection of entities within a DbContext. It provides methods for querying, adding, updating, and deleting records. Each DbSet typically maps to a table in the database. Developers use DbSet together with LINQ to perform strongly typed database operations while maintaining compile-time safety.
5. How does EF Core communicate with a database?
EF Core uses database providers to translate LINQ expressions into SQL statements. When a query is executed, EF Core converts the LINQ expression tree into provider-specific SQL and sends it to the database engine. The results are then mapped back into .NET objects. This abstraction allows developers to switch database providers with minimal code changes.
6. What is Change Tracking?
Change Tracking is a mechanism that allows EF Core to monitor entity modifications. When entities are loaded through a DbContext, EF Core keeps track of their state. Any changes made to properties are detected and translated into INSERT, UPDATE, or DELETE statements during SaveChanges. This feature simplifies data persistence but can introduce performance overhead when working with large datasets.
7. What is the difference between EF6 and EF Core?
EF Core is a complete redesign of Entity Framework. It is lightweight, cross-platform, open-source, and optimized for modern .NET applications. EF Core supports better performance, improved LINQ translation, and cloud-native architectures. Although EF6 still exists, most new projects use EF Core because it aligns with current .NET development practices.
8. What is Code First?
Code First is an approach where developers define entities and relationships in C# classes. EF Core then generates the database schema through migrations. This approach is popular because it keeps domain models and database design closely aligned. Most modern ASP.NET Core applications follow the Code First approach.
9. What is Database First?
Database First starts with an existing database schema. EF Core scaffolds entity classes and DbContext definitions from database tables, views, and relationships. This approach is useful when integrating with legacy systems or existing databases managed by database administrators.
10. What are Migrations?
Migrations allow developers to evolve a database schema alongside application code. EF Core generates migration files that describe schema changes such as creating tables, adding columns, modifying relationships, and updating indexes. Migrations provide version control for database structures and simplify deployment across environments.
🎁 Free .NET Interview PDF
Download 150 Real .NET Interview Questions
Includes C#, ASP.NET Core, Entity Framework, Async/Await, LINQ, System Design, Caching, Microservices and more.
No spam. Unsubscribe anytime.
11. What is EntityState?
EntityState represents the current status of an entity being tracked by Entity Framework Core. EF Core uses entity states such as Added, Modified, Deleted, Unchanged, and Detached to determine what database operations should be executed when SaveChanges is called. For example, an entity marked as Added will generate an INSERT statement, while an entity marked as Modified will generate an UPDATE statement. Understanding entity states is important because EF Core relies on them to synchronize in-memory objects with database records efficiently. Interviewers often ask about EntityState to evaluate a developer's understanding of how EF Core tracks and persists changes.
12. What is ChangeTracker?
ChangeTracker is the component responsible for monitoring entity changes within a DbContext. Whenever entities are loaded through EF Core, the ChangeTracker keeps track of their original values and current values. When SaveChanges is executed, EF Core compares these values and determines which SQL operations need to be generated. While ChangeTracker simplifies data persistence, it also consumes memory and processing resources. In high-performance scenarios involving large read-only datasets, developers often disable tracking to improve efficiency. A solid understanding of ChangeTracker is essential for diagnosing performance issues and understanding EF Core's internal behavior.
13. What is AsNoTracking()?
AsNoTracking is a query optimization feature that disables entity tracking for a specific query. By default, EF Core tracks all entities returned from a query. This tracking enables updates but introduces memory and CPU overhead. When data is only being read and will not be modified, tracking is unnecessary. Using AsNoTracking improves query performance, reduces memory usage, and decreases the workload of the ChangeTracker. It is particularly beneficial in reporting systems, dashboards, APIs, and other read-heavy applications. Many senior-level interviews include questions about AsNoTracking because it is one of the simplest and most effective EF Core performance optimizations.
14. When should AsNoTracking be used?
AsNoTracking should be used whenever entities are retrieved for read-only purposes and no updates will be performed. Examples include API endpoints that return data to clients, reporting dashboards, search results, analytics systems, and data export operations. In these scenarios, tracking entities provides no value and only consumes resources. However, AsNoTracking should be avoided when entities need to be updated later because EF Core will not automatically detect changes. Developers would need to manually attach entities back to the DbContext. Understanding when to use AsNoTracking demonstrates an awareness of both performance optimization and EF Core's change tracking behavior.
15. What is AutoDetectChanges?
AutoDetectChanges is a feature that automatically scans tracked entities to determine whether any properties have been modified. EF Core uses this mechanism before operations such as SaveChanges to ensure that updates are accurately detected and persisted to the database. Although AutoDetectChanges improves developer productivity, it can introduce performance overhead when working with large numbers of tracked entities. In bulk processing scenarios, developers sometimes disable automatic change detection temporarily and manually invoke detection when necessary. Senior developers should understand the trade-offs between convenience and performance when working with AutoDetectChanges.
16. What is eager loading?
Eager loading is a technique for retrieving related entities together with the primary entity in a single query. It is typically implemented using Include and ThenInclude methods. For example, when loading Orders, a developer may also load related Customer information in the same database request. Eager loading helps reduce additional database round trips and can prevent performance issues such as the N+1 query problem. However, loading too much related data can increase query complexity and memory usage. Choosing the correct loading strategy is a common discussion topic in Entity Framework Core interviews.
17. What is lazy loading?
Lazy loading is a strategy where related entities are not loaded immediately but are retrieved only when accessed. For example, an Order entity may be loaded first, while the related Customer entity is retrieved later when the Customer property is accessed. Lazy loading can simplify development because related data appears automatically available. However, it can also introduce hidden database queries and performance problems, particularly when processing large collections. Many developers unintentionally create N+1 query issues through excessive use of lazy loading. Understanding its benefits and risks is important for designing efficient applications.
18. What is explicit loading?
Explicit loading is a strategy where related entities are loaded manually when required. Unlike eager loading, which retrieves related data immediately, explicit loading gives developers full control over when additional queries are executed. This approach is useful when related data is only needed under certain conditions. By loading data selectively, developers can balance performance and flexibility. Explicit loading is often preferred in scenarios where eager loading would retrieve unnecessary information but lazy loading could generate excessive database queries.
19. What is Include()?
Include is an EF Core method used to eagerly load related entities as part of the same query. For example, when retrieving Orders, Include can be used to also retrieve associated Customers. This allows related data to be available immediately without issuing additional database requests. Include improves developer productivity and helps prevent common performance issues such as repeated database queries. However, excessive use of Include can result in large and complex SQL statements. Interviewers often ask about Include because understanding relationship loading strategies is essential for building efficient EF Core applications.
20. What is ThenInclude()?
ThenInclude extends the functionality of Include by allowing developers to load deeper levels of related entities. For example, an application may load Orders, then Customers, and then CustomerAddresses through a chain of Include and ThenInclude calls. This capability is useful when working with complex object graphs that contain multiple relationship levels. However, developers should be careful not to load excessive data because query complexity and memory usage can grow quickly. Understanding ThenInclude demonstrates familiarity with advanced relationship management in Entity Framework Core.
21. What are navigation properties?
Navigation properties are properties that represent relationships between entities in Entity Framework Core. They allow developers to navigate from one entity to related entities using object references rather than manually joining tables. For example, an Order may contain a Customer navigation property, while a Customer may contain a collection of Orders. Navigation properties improve readability and make object-oriented data access more intuitive. They also enable features such as eager loading, lazy loading, and explicit loading. A strong understanding of navigation properties is essential when designing domain models and working with relational data.
22. What is the N+1 query problem?
The N+1 query problem occurs when an application executes one query to retrieve a collection of entities and then executes additional queries for each related entity. For example, loading 100 Orders and then issuing 100 separate queries to load Customer information results in 101 database queries. This can significantly increase latency and database load. The N+1 problem is one of the most common performance issues in ORM-based applications. Developers can avoid it by using eager loading, projections, or carefully designed query strategies. Interviewers frequently ask about the N+1 problem because it demonstrates a developer's awareness of real-world performance challenges.
23. How can N+1 queries be avoided?
N+1 queries can be avoided by reducing unnecessary database round trips and retrieving related data more efficiently. Common solutions include eager loading with Include, projecting required fields with Select, batching requests, and designing queries that retrieve all required data at once. Developers should also monitor generated SQL and use profiling tools to identify inefficient query patterns. Simply relying on lazy loading without understanding its implications often leads to N+1 problems. Being able to recognize and solve N+1 issues is an important skill for building scalable applications.
24. What is projection?
Projection is the process of selecting only the specific fields required by an application rather than loading entire entities. In EF Core, projection is commonly implemented using the Select method. Instead of retrieving all columns from a table, developers can return only the properties needed for a particular operation. Projection improves performance by reducing data transfer, memory consumption, and query complexity. It is particularly useful in APIs, reporting systems, and high-traffic applications. Many senior developers prefer projection over loading full entities when updates are not required.
25. Why use Select() instead of Include()?
Select is often more efficient than Include because it retrieves only the data that is actually needed. Include loads entire related entities, which may contain many properties that are never used by the application. In contrast, Select allows developers to shape the query result and return only the required fields. This reduces memory usage, decreases network traffic, and improves overall query performance. In large-scale systems, projection through Select is often considered a best practice. Understanding when to use Select instead of Include is a common topic in performance-focused EF Core interviews.
🎁 Free .NET Interview PDF
Download 150 Real .NET Interview Questions
Includes C#, ASP.NET Core, Entity Framework, Async/Await, LINQ, System Design, Caching, Microservices and more.
No spam. Unsubscribe anytime.
26. What are compiled queries?
Compiled queries are precompiled query definitions that reduce the overhead of repeatedly translating LINQ expressions into SQL. Normally, EF Core must process and compile a query before execution. When the same query is executed frequently, compiled queries allow that work to be reused. This optimization can improve performance in high-throughput applications where specific queries are executed thousands of times per second. However, compiled queries add complexity and should only be used when profiling demonstrates a measurable benefit. They are generally considered an advanced optimization technique.
27. What is query compilation?
Query compilation is the process of translating a LINQ expression into an executable SQL statement. When a query is executed, EF Core analyzes the expression tree, applies provider-specific logic, generates SQL, and prepares the execution plan. This process introduces some overhead, particularly for complex queries. To improve performance, EF Core caches query plans whenever possible. Understanding query compilation helps developers identify opportunities for optimization and better understand how LINQ interacts with relational databases.
28. What is batching?
Batching is a performance optimization technique that combines multiple database operations into fewer round trips. Instead of sending individual commands separately, EF Core can group multiple INSERT, UPDATE, or DELETE operations together. This reduces network overhead and improves overall throughput. Batching is especially beneficial when processing large numbers of entities because database communication is often one of the most expensive parts of an application. Modern versions of EF Core include automatic batching support to improve efficiency.
29. What is connection pooling?
Connection pooling is a mechanism that reuses existing database connections instead of creating new ones for every request. Opening and closing database connections is relatively expensive. Connection pools maintain a collection of reusable connections that can be quickly assigned to application requests. This significantly improves performance, reduces resource consumption, and increases scalability under heavy load. Most modern database providers support connection pooling automatically. Understanding connection pooling is important because many database performance issues are related to inefficient connection management rather than query execution itself.
30. How do you optimize EF Core performance?
Optimizing EF Core performance requires a combination of efficient query design, proper indexing, and minimizing unnecessary work. Common techniques include using AsNoTracking for read-only queries, projecting only required fields with Select, avoiding N+1 query problems, implementing proper database indexes, and leveraging batching for bulk operations. Developers should also monitor generated SQL, profile slow queries, and avoid loading large object graphs unnecessarily. Performance optimization should always be driven by measurement rather than assumptions. Senior-level interviews often focus on EF Core performance because inefficient database access can become a major bottleneck in production systems.
31. What is ExecuteUpdate()?
ExecuteUpdate is a feature introduced in modern versions of EF Core that allows bulk updates directly in the database. Instead of loading entities into memory, modifying them, and calling SaveChanges, ExecuteUpdate generates a direct SQL UPDATE statement that executes on the database server. This significantly improves performance when updating large numbers of records because it reduces memory usage, network traffic, and change-tracking overhead. Developers should consider ExecuteUpdate whenever they need to perform large-scale updates efficiently.
32. What is ExecuteDelete()?
ExecuteDelete allows bulk deletion of records directly within the database without loading entities into memory. Traditional deletion workflows require retrieving entities first and then calling Remove or RemoveRange. ExecuteDelete eliminates this overhead by generating a direct SQL DELETE statement. This approach improves performance and reduces resource consumption, especially when removing large volumes of data. It is particularly useful in cleanup jobs, archival processes, and administrative operations.
33. What is a transaction?
A transaction is a mechanism that ensures multiple database operations succeed or fail together as a single unit. If any operation within the transaction fails, all changes can be rolled back to preserve data consistency. This guarantees that the database remains in a valid state even when errors occur. Transactions are critical in financial systems, e-commerce platforms, and other applications where partial updates could lead to data corruption. Understanding transactions is fundamental for building reliable and consistent applications.
34. What is optimistic concurrency?
Optimistic concurrency is a strategy for handling situations where multiple users attempt to modify the same data simultaneously. Instead of locking records during editing, optimistic concurrency assumes conflicts are rare and verifies that data has not changed before saving updates. If another user has already modified the record, EF Core can detect the conflict and throw an exception. This approach improves scalability because database locks are minimized. It is commonly used in web applications where many users may access the same data concurrently. Understanding optimistic concurrency is important for designing systems that maintain data consistency while supporting high levels of concurrency.
35. What is RowVersion?
RowVersion is a special database-generated value commonly used for optimistic concurrency control. Each time a row is updated, the database automatically generates a new RowVersion value. EF Core can compare the original RowVersion with the current database value to determine whether another process has modified the record. If the values do not match, EF Core detects a concurrency conflict and can prevent accidental overwrites. RowVersion is widely used because it provides a simple and efficient mechanism for concurrency management.
36. What is a Repository Pattern?
The Repository Pattern is a design pattern that abstracts data access logic behind a collection-like interface. Instead of interacting directly with EF Core, application code communicates with repositories that expose methods such as GetById, Add, Update, and Delete. The goal is to separate business logic from data access concerns and improve maintainability. However, excessive abstraction can sometimes add unnecessary complexity. Repository Pattern discussions are common in .NET interviews because developers often debate its role alongside EF Core.
37. Should EF Core use Repository Pattern?
This is a common interview question because there is no universal answer. Some developers argue that EF Core already implements repository-like behavior through DbSet and Unit of Work behavior through DbContext. Adding another repository layer may introduce unnecessary abstraction. Others prefer repositories because they provide a clear boundary between application logic and persistence logic, making testing and architecture decisions easier. A strong answer should discuss trade-offs rather than claiming one approach is always correct.
38. What is Unit of Work?
Unit of Work is a design pattern that coordinates changes across multiple entities and commits them as a single transaction. The pattern tracks modifications, insertions, and deletions during a business operation and persists them together when a commit occurs. This ensures consistency and reduces the risk of partial updates. Unit of Work is particularly useful when multiple repositories participate in the same business process. Understanding Unit of Work helps developers design transactional systems that maintain data integrity.
39. Is DbContext a Unit of Work?
Yes. DbContext naturally implements many Unit of Work responsibilities. It tracks entity changes, manages transactions, and persists updates through SaveChanges. Because of this, many developers consider an additional Unit of Work layer unnecessary when using EF Core. However, some architectures still introduce a custom Unit of Work abstraction for consistency, testing, or framework independence. Interviewers often ask this question to assess architectural understanding rather than knowledge of a specific API.
40. How do you implement transactions in EF Core?
Transactions can be implemented using Database.BeginTransaction, TransactionScope, or implicit transaction behavior provided by SaveChanges. For simple operations, SaveChanges automatically wraps modifications in a transaction. For more complex workflows involving multiple operations, developers can manually create transactions and control commit or rollback behavior. Proper transaction management is critical for maintaining consistency when multiple database changes must succeed or fail together. A senior developer should understand both automatic and explicit transaction handling strategies.
41. What is query splitting?
Query splitting is a feature that allows EF Core to execute multiple SQL queries instead of generating a single large join query. This approach can reduce memory consumption and avoid issues caused by complex joins. EF Core then combines the results into the expected object graph. Query splitting is especially useful when loading multiple collections that would otherwise create very large result sets. Understanding query splitting helps developers balance performance and query complexity.
42. What is a cartesian explosion?
A cartesian explosion occurs when joins between multiple related tables generate a large number of duplicated result rows. For example, loading Customers, Orders, and OrderItems in a single query can produce many repeated values because every combination of related records appears in the result set. This can dramatically increase network traffic, memory usage, and query execution time. Query splitting and careful data shaping are common techniques used to avoid cartesian explosion problems.
43. How does EF Core support Dependency Injection?
EF Core integrates directly with ASP.NET Core's built-in Dependency Injection system. Developers can register DbContext instances through the service container and inject them into controllers, services, repositories, or background workers. This approach promotes loose coupling, simplifies testing, and ensures proper lifetime management. Dependency Injection is considered a core architectural practice in modern .NET applications.
44. What is a shadow property?
A shadow property is a property that exists within the EF Core model but is not defined in the entity class itself. EF Core maintains the value internally and maps it to a database column. Shadow properties are often used for auditing fields such as CreatedDate, UpdatedDate, or TenantId. They allow developers to store metadata without polluting domain models with infrastructure concerns. Although less common than regular properties, shadow properties are useful in advanced EF Core scenarios.
45. What is value conversion?
Value conversion is a feature that transforms values between CLR types and database types. For example, an enum can be stored as a string in the database rather than as an integer. EF Core automatically performs conversions when reading and writing data. Value converters improve flexibility and can simplify database design while preserving strong typing in application code. Understanding value conversion demonstrates familiarity with advanced mapping capabilities.
46. How do you seed data in EF Core?
Data seeding allows predefined records to be inserted into a database during migrations or initialization. EF Core supports seeding through the HasData method in model configuration. Common examples include reference tables, default roles, countries, or application settings. Seeding ensures that required data exists consistently across environments and deployments. It is particularly useful when setting up development, testing, and production databases.
47. How do you handle large datasets?
Large datasets should be processed using techniques that minimize memory consumption and database overhead. Common approaches include pagination, projection, streaming, batching, filtering, and proper indexing. Loading millions of records into memory at once is rarely a good idea. Developers should also consider asynchronous processing and background jobs when handling large volumes of data. A strong answer should focus on scalability and resource efficiency rather than a single optimization technique.
48. How do you debug generated SQL?
EF Core provides several ways to inspect generated SQL statements. Developers can enable logging, use application monitoring tools, or call ToQueryString to view the exact SQL produced by a LINQ query. Inspecting generated SQL is often the fastest way to identify inefficient queries, missing filters, unnecessary joins, or N+1 query problems. Senior developers regularly analyze generated SQL when diagnosing performance issues.
49. How would you use EF Core in a microservice architecture?
In a microservice architecture, each service should own its database and manage its own EF Core DbContext independently. Services should avoid sharing databases because this creates tight coupling and reduces autonomy. Instead, communication should occur through APIs, events, or message queues. EF Core remains a popular choice for persistence within individual services because it provides productivity and strong integration with ASP.NET Core. Interviewers often ask this question to evaluate understanding of both EF Core and distributed system design.
50. What are the most common EF Core mistakes developers make?
Common mistakes include creating N+1 query problems, loading entire entities when projections would suffice, overusing tracking, ignoring indexes, and misunderstanding DbContext lifetimes. Other frequent issues include excessive lazy loading, inefficient transactions, failure to monitor generated SQL, and poor handling of concurrency conflicts. Most EF Core performance problems are not caused by the framework itself but by inefficient usage patterns. A senior developer should understand these pitfalls and know how to identify and resolve them before they impact production systems.
Related Interview Guides
Ready for Senior .NET Interviews?
Get access to 200+ interview questions covering C#, EF Core, ASP.NET Core, System Design, Microservices, Redis and Async/Await.
Get .NET Interview Mastery Pro