Entity Framework Core: Data Access and ORM Concepts – .Net Core Interview Questions and Answers

Q1: What is Entity Framework Core, and how does it differ from Entity Framework 6?
Answer:
Entity Framework Core (EF Core) is a modern, lightweight, and cross-platform Object-Relational Mapper (ORM) for .NET Core. It allows developers to interact with databases using C# objects. Unlike Entity Framework 6, which is part of the .NET Framework and Windows-only, EF Core supports multiple database providers and works on different platforms (Windows, Linux, macOS). It also has better performance and supports new features like in-memory databases and no-tracking queries.

Q2: What are migrations in Entity Framework Core? How do they work?
Answer:
Migrations in EF Core are a way to update the database schema to match changes in your application’s data model. You generate migrations using the Add-Migration command in the Package Manager Console. EF Core will track changes to the model, and when a migration is applied, it will create the necessary SQL commands to update the database schema.

Q3: How would you manage a many-to-many relationship using EF Core?
Answer:
EF Core supports many-to-many relationships by automatically creating a join table. You define two entities with navigation properties to each other. For example, in a Student and Course relationship, you can use a StudentCourses join table. EF Core will handle the creation of this table when you generate migrations.

Q4: Explain how to use lazy loading and eager loading in EF Core.
Answer:

  • Lazy Loading: EF Core supports lazy loading, where related entities are loaded only when accessed. You enable it by adding the virtual keyword to navigation properties and configuring lazy loading in Startup.cs.

  • Eager Loading: With eager loading, related entities are loaded with the initial query using Include(). This is useful when you know you’ll need related data upfront.

Q5: How can you improve the performance of a query in Entity Framework Core?
Answer:

  • Use AsNoTracking() for read-only queries to avoid unnecessary tracking of entity state.

  • Optimize Include() queries to avoid loading unnecessary related entities.

  • Use batching to send fewer database queries.

  • Use compiled queries for frequently executed queries to reduce query parsing overhead.