Building-Cloud-Native-Core-Applications :👈 👉:Redis-QA

N+1 query problem in Entity Framework Core Interview Questions

n+1 Query Problem – Important Interview Questions

Q1. What is the N+1 Query Problem?

Answer: The N+1 Query Problem occurs when an application executes one query to retrieve a collection of records and then executes an additional query for each record to retrieve related information.

Q2. Why does the N+1 Query Problem occur in Entity Framework Core?

Answer: It commonly occurs when lazy loading is enabled and navigation properties are accessed inside loops. It can also occur when developers repeatedly call database-backed service methods for individual records.

Q3. How do you prevent N+1 queries?

Answer: Use eager loading with Include() and ThenInclude(), projection with Select(), batch queries, and carefully designed database access patterns.

Q4. What is the difference between eager loading and lazy loading?

Answer:

  • Eager loading retrieves related data as part of the initial query execution.
  • Lazy loading retrieves related data when a navigation property is accessed.

Q5. Is Include() always the best solution?

Answer: No. Include() is useful when complete related entities are required. For API responses and reporting, Select() projection is often better because it retrieves only the necessary columns.

Q6. What is the difference between AsSplitQuery() and AsSingleQuery()?

Answer:

  • AsSingleQuery() loads related data using one SQL query, typically involving joins.
  • AsSplitQuery() executes multiple SQL queries to retrieve the related collections separately.

Q7. Can pagination solve the N+1 problem?

Answer: Pagination reduces the number of parent records retrieved, which can reduce the number of additional queries. However, it does not eliminate the N+1 pattern itself. Combine pagination with projection or eager loading.

Q8. How do you identify N+1 queries in production?

Answer: Use application monitoring, EF Core logging, database monitoring, SQL Profiler or Extended Events to identify repeated queries associated with individual HTTP requests.

Q9. What is Cartesian Explosion?

Answer: Cartesian explosion occurs when multiple related collections are joined together and produce a large number of duplicated rows. AsSplitQuery() can help avoid this in suitable scenarios.

Q10. What is your preferred approach for a high-performance ASP.NET Core API?

Answer: For read-only API endpoints, I generally prefer Select() projection into DTOs, pagination, appropriate indexes and AsNoTracking() when applicable. I also inspect generated SQL and measure performance before deciding whether Include() or AsSplitQuery() is appropriate.

🔙
Building-Cloud-Native-Core-Applications :👈 👉:Redis-QA