MCSD Entity Framework and Data Access 2 — Questions and Answers
Question 1: Which Entity Framework method is used to eagerly load a related entity in a query?
- .Join()
- .Include() (Correct answer)
- .Attach()
- .Load()
Correct answer: .Include()
The `.Include()` method tells Entity Framework to fetch related entities in the same SQL query using a JOIN.
Question 2: What is the Repository pattern used for in .NET data access?
- Caching database results
- Abstracting data access logic behind an interface to decouple it from business logic (Correct answer)
- Managing database migrations
- Pooling database connections
Correct answer: Abstracting data access logic behind an interface to decouple it from business logic
The Repository pattern encapsulates data access logic behind an abstraction, making business logic independent of the data source.
Question 3: In Entity Framework, what does `SaveChanges()` do?
- Rolls back the transaction
- Persists all tracked entity changes to the database in a single transaction (Correct answer)
- Reloads entities from the database
- Validates all entity data annotations
Correct answer: Persists all tracked entity changes to the database in a single transaction
`SaveChanges()` commits all pending Add, Modify, and Delete operations tracked by the DbContext to the database.
Question 4: What does the `AsNoTracking()` method do in Entity Framework?
- Disables lazy loading
- Returns entities without change tracking, improving performance for read-only queries (Correct answer)
- Prevents SQL injection
- Disables migrations
Correct answer: Returns entities without change tracking, improving performance for read-only queries
`AsNoTracking()` returns entities that the DbContext does not track, reducing memory overhead for read-only scenarios.
Question 5: Which approach in Entity Framework generates database tables from existing C# classes?
- Database-First
- Model-First
- Code-First (Correct answer)
- Schema-First
Correct answer: Code-First
Code-First allows developers to define the database schema using C# classes, and EF generates or migrates the database tables.
Question 6: What is the purpose of a DbSet<T> property in a DbContext class?
- Defines a stored procedure
- Represents a table in the database and provides querying capabilities for that entity (Correct answer)
- Configures the database connection
- Maps enum values to strings
Correct answer: Represents a table in the database and provides querying capabilities for that entity
A `DbSet<T>` represents the collection of all entities of a given type, corresponding to a database table.
Which Entity Framework method is used to eagerly load a related entity in a query?