ORMs: Entity Framework Core and Hibernate Interview Questions

261 multiple-choice tech interview questions on ORMs: Entity Framework Core and Hibernate: mapping, change tracking, lazy and eager loading, N+1, migrations, raw SQL and performance. Written for technical phone screens and interview prep, organized by subtopic, with a short explanation for every answer. Learn the 242 key terms with the flashcards first, then test yourself.

Take the practice test · Flashcards · All study tools

What it covers

  1. 7.1 ORM fundamentals and mapping concepts
  2. 7.2 EF Core modeling and configuration
  3. 7.3 EF Core querying and LINQ translation
  4. 7.4 Loading related data and the N+1 problem
  5. 7.5 Change tracking, saving and transactions
  6. 7.6 Migrations and schema management
  7. 7.7 Hibernate and JPA
  8. 7.8 Other ORMs and data access libraries
  9. 7.9 ORM performance, testing and pitfalls

Key terms

7.1 ORM fundamentals and mapping concepts

Proxy requirements
Overridable members
Identity map
One object per row
Database-first
Scaffold from schema
Query builder
SQL without mapping
SQL still matters
Read generated SQL
One-to-many in classes
Collection and reference
Dirty checking
Compare to snapshot
Detached entity
Not tracked
ORM fit
CRUD and rich domain
ORM misfit
Reporting and bulk
Mixing raw SQL
Use both
Database-agnostic myth
Still differs
EF Core provider
Database translator
Convention over configuration
Defaults
Hydration
Rows to objects
Cascading save
Save related
Orphan removal
Delete removed children
Entity equality
Unsaved IDs
Composite key mapping
Several properties
Enum storage
Integers by default
Async queries
Free threads
Client-generated keys
IDs before save
HiLo
ID blocks
Flush
Send pending changes
Interceptors
Hooks around saves
Metadata model
Mapping definitions
Generated ID readback
RETURNING or OUTPUT
Join entity with payload
Explicit mapping

7.2 EF Core modeling and configuration

ORM
Object-relational mapper: maps classes to tables and generates SQL
DbContext
EF Core's unit of work that tracks entities and saves changes
Change tracking
Recording which loaded entities changed so the ORM can write updates
Key convention
Id or TypeNameId
Annotations vs Fluent API
Fluent wins
IEntityTypeConfiguration
Per-entity config
Complex types
EF Core 8 value types
Shadow property
Not on class
Value converter
Type conversion
Enum as string
HasConversion<string>
Global query filter
Automatic WHERE
IgnoreQueryFilters
Bypass filters
Named query filters
EF Core 10
TPH
Default inheritance
TPC
EF Core 7
ToJson
JSON columns
Primitive collections
EF Core 8
Skip navigations
Implicit join table
Required relationship
FK nullability
Default cascade
Required FKs
Unique index
HasIndex IsUnique
HasPrecision
Decimal scale
HasMaxLength
Column length
Keyless entities
Views and raw SQL
Entity splitting
One entity, many tables
HasData
Seed data
Backing field
Private field mapping
Temporal tables
IsTemporal

7.3 EF Core querying and LINQ translation

Client evaluation
Throws except final Select
Find
Checks tracker first
SingleAsync
Exactly one
AnyAsync
EXISTS
Offset paging
OrderBy, Skip, Take
Stable order
OrderBy before paging
Contains to IN
IN list or array parameter
String Contains
LIKE with leading %
EF.Functions.Like
SQL LIKE
Collation decides case
Database rules
GroupBy translation
Aggregates
SqlQuery<T>
Unmapped raw SQL
EF.Constant
Inline constant
TagWith
SQL comment
AsAsyncEnumerable
Streaming
Left join
GroupJoin or LeftJoin
Navigation in Select
Implicit JOIN
Custom methods
Not translatable
Expression predicate
Reusable filter
Captured variables
Parameters
UtcNow in queries
Server time
Union and Concat
UNION, UNION ALL
ExecuteSqlAsync
Rows affected
ToDictionaryAsync
In-memory dictionary

7.4 Loading related data and the N+1 problem

Lazy loading
Loading related data the first time a navigation property is accessed
Eager loading
Loading related data up front, such as with Include or JOIN FETCH
Projection
Selecting only specific fields into a DTO instead of full entities
Split query
Loading each included collection in its own SQL query to avoid row explosion
ThenInclude
Deeper level
AsSplitQuery
Query per collection
Split query risk
Inconsistent snapshot
Filtered Include
Matching children
Explicit loading
Load on demand
Lazy loading opt-in
Proxies or ILazyLoader
Disposed context
Lazy load fails
Serializer lazy loads
Hidden queries
Navigation cycles
Serialization loops
AutoInclude
Always included
@BatchSize
IN-batched loads
Entity graph
Fetch plan
JOIN FETCH paging
In-memory paging
Over-including
Wasted I/O
Relationship fix-up
Auto-linking
Manual batch load
Contains query
Counting in SQL
Project Count()
SUBSELECT fetch
One subselect
Identity resolution
Shared instances
Include with Select
Ignored
Reference includes
No row multiplication
Acceptable lazy loading
Small, short-lived
LoadAsync on query
Fill tracker

7.5 Change tracking, saving and transactions

Entity states
Five states
Update vs Attach
Modified vs unchanged
Changed columns only
Partial UPDATE
SaveChanges transaction
Atomic by default
BeginTransactionAsync
Span saves
Execution strategy
Retry whole block
EnableRetryOnFailure
Transient retries
Insert batching
Fewer round trips
ChangeTracker.Clear
Stop tracking
DetectChanges cost
Snapshot compare
Concurrency conflict
Reload and retry
IsConcurrencyToken
Original value in WHERE
xmin
PostgreSQL row version
ExecuteUpdate catch
Skips tracker
Audit timestamps
Interceptor
Savepoints
Partial rollback
TransactionScope async
Flow option
Adding graphs
All inserted
Delete without load
Stub or ExecuteDelete
Disconnected update
Load and copy
OriginalValues
Tracked originals
Bulk copy
SqlBulkCopy or COPY
Update overwrite risk
Missing fields
IsModified
One property
UseTransaction
Share ADO.NET transaction

7.6 Migrations and schema management

Migration
A versioned, code-defined change to the database schema
Concurrency token
A column checked on update to detect conflicting changes
migrations add
Create migration
database update
Apply migrations
Model snapshot
Diff baseline
migrations remove
Undo last unapplied
Idempotent script
Apply missing only
__EFMigrationsHistory
Applied list
Rename review
Drop and add risk
migrationBuilder.Sql
Custom SQL
Migration bundle
Executable
Per-provider migrations
Separate assemblies
IDesignTimeDbContextFactory
Tool-time context
Pending model changes
EF Core 9 error
EnsureCreated
No history
Squashing
New baseline
has-pending-model-changes
CI check
hbm2ddl validate
Check only
hbm2ddl create-drop
Test schemas
Liquibase formats
XML, YAML, JSON, SQL
Alembic
SQLAlchemy migrations
prisma migrate dev
Dev migrations
prisma db push
Prototype sync
drizzle-kit
SQL from TypeScript
Migration lock
One runner
Entities in old migrations
Avoid
Migration timeout
Long changes
--context
Choose DbContext

7.7 Hibernate and JPA

JPA entity states
New, managed, detached, removed
persist vs merge
New vs detached
merge return value
Managed copy
LazyInitializationException
Closed session
Open Session in View
Lazy loads in views
IDENTITY generation
No insert batching
@Version
Optimistic locking
PESSIMISTIC_WRITE
Row lock
Owning side
Holds the FK
mappedBy
Inverse side
Bidirectional helpers
Keep both sides
REMOVE on many-to-many
Shared row deletes
JPQL
Entity queries
Criteria API
Type-safe dynamic queries
Native query
Database SQL
Constructor expression
DTO projection
AUTO flush
Flush before query
Read-only sessions
Skip dirty checks
Second-level cache providers
Ehcache, Infinispan
Query cache
Cached result IDs
@Inheritance
Mapping strategy
StatelessSession
Bulk without context
jdbc.batch_size
JDBC batching
Hibernate 7
Jakarta Persistence 3.2
Panache
Quarkus simplification
Hibernate statistics
Query counts

7.8 Other ORMs and data access libraries

Dapper QueryAsync
Parameterized mapping
splitOn
Multi-mapping
QueryMultipleAsync
Several result sets
SQLAlchemy Core vs ORM
SQL vs objects
SQLAlchemy 2.0 select
New query style
SQLAlchemy Session
Tracks and flushes
selectinload
IN-query loading
expire_on_commit
Reload after commit
AsyncSession lazy loads
Not allowed
SQLModel
SQLAlchemy plus Pydantic
schema.prisma
Prisma models
include vs select
Relations vs fields
Prisma 7
Rust-free client
$transaction
Prisma transactions
Drizzle design
Thin SQL-like API
TypeORM
Decorator ORM
Sequelize
Promise-based ORM
MikroORM
Unit of Work
jOOQ
Type-safe SQL
MyBatis
SQL mappers
JdbcClient
Fluent JDBC
Exposed
Kotlin SQL
GORM
Go ORM
sqlc
Code from SQL
Diesel
Rust ORM
EF6 vs EF Core
Legacy vs rewrite
Kysely
TypeScript query builder
Ecto
Elixir data mapping

7.9 ORM performance, testing and pitfalls

Translation cache
Reused shapes
Query shape explosion
Many translations
NoTracking default
Context option
Sensitive data logging
Off in production
Slow query logging
Durations and interceptors
Respawn
Reset test data
SQL snapshot tests
Catch changes
Upgrade notes
Translation changes
Matching indexes
ORM won't create
IsUnicode(false)
varchar mapping
Default split queries
Provider option
First-query warm-up
Model build
Stored procedure saves
EF Core 7
SetCommandTimeout
Longer timeout
Read replica context
Second connection
Tenant query filter
Shared tables
ValueComparer
Detect in-place changes
Unawaited SaveChangesAsync
Lost errors
Unique violation handling
DbUpdateException
Npgsql UTC rule
timestamptz
Migration CI test
Fresh database
Mocking DbSet
Hides translation bugs
Bounded queries
Page or limit
Database defaults
Omitted and read back
TagWithCallSite
Source location
SaveChanges in loops
Save once
Upserts
MERGE or ON CONFLICT
StringComparison overloads
Not translated

Sample practice questions

  1. What problem does an object-relational mapper (ORM) solve?

    1. It replaces the database entirely with objects held in application memory
    2. It converts a relational SQL database into a NoSQL document database
    3. It automatically designs the optimal schema for any given workload
    4. It maps objects to tables and generates SQL, replacing hand-written data access

    Answer: D. It maps objects to tables and generates SQL, replacing hand-written data access The mismatch between object graphs and relational tables is called the object-relational impedance mismatch.

  2. In Entity Framework Core, what is a DbContext?

    1. The connection string used to reach the database server
    2. A generated migration file describing schema changes
    3. A unit of work that tracks entities and saves their changes
    4. A wrapper class that calls the database's stored procedures

    Answer: C. A unit of work that tracks entities and saves their changes A DbContext is lightweight and meant to be short-lived, typically one per web request.

  3. In EF Core, when does a LINQ query like `context.Users.Where(u => u.IsActive)` actually execute against the database?

    1. Immediately, as soon as the `Where` line has run
    2. When enumerated, as by `ToListAsync()` or a `foreach`
    3. When the DbContext instance is first constructed
    4. When `SaveChanges` is next called on the context

    Answer: B. When enumerated, as by `ToListAsync()` or a `foreach` IQueryable builds an expression tree; execution is deferred until results are needed.

  4. What is lazy loading in an ORM?

    1. All related data is loaded up front in the very first query
    2. Data is only loaded once, while the application is starting
    3. Related data loads on first access to a navigation property
    4. Queries are deferred until the database server is idle

    Answer: C. Related data loads on first access to a navigation property Lazy loading is convenient but easily causes N+1 queries. EF Core needs proxies or explicit setup to enable it.

  5. What does EF Core's change tracker do when you call `SaveChanges()`?

    1. Saves every loaded entity to the database again, changed or not
    2. Commits only the entities explicitly marked with a [Save] attribute
    3. Writes the pending changes to a log file instead of the database
    4. Finds added, modified and deleted entities and sends matching SQL

    Answer: D. Finds added, modified and deleted entities and sends matching SQL By default SaveChanges wraps its statements in a transaction.

  6. What is an EF Core migration?

    1. A copy of the database moved over to a new server
    2. A scheduled backup of the database's data files
    3. Generated Up and Down code describing a schema change
    4. A change made to the app's connection string

    Answer: C. Generated Up and Down code describing a schema change `dotnet ef migrations add Name` creates one; `dotnet ef database update` or a generated SQL script applies it.

  7. In Hibernate (and JPA), which object plays the role similar to EF Core's DbContext?

    1. The SessionFactory, built once per app
    2. The Dialect, chosen per database
    3. The Session (EntityManager in JPA)
    4. The DataSource, managing connections

    Answer: C. The Session (EntityManager in JPA) The SessionFactory is the expensive, thread-safe factory created once; sessions are short-lived units of work.

  8. What is the main tradeoff of using an ORM compared with a micro-ORM such as Dapper?

    1. ORMs can't run queries at all, while micro-ORMs can run any query
    2. Micro-ORMs require far more database permissions than full ORMs do
    3. ORMs only work with NoSQL databases, while micro-ORMs need SQL
    4. Faster development and tracking, but less SQL control and some overhead

    Answer: D. Faster development and tracking, but less SQL control and some overhead Many teams mix them: an ORM for most work and Dapper or raw SQL for hot paths.

  9. What does EF Core's compiled model or compiled query feature mainly improve?

    1. The amount of disk space the database files take up
    2. Startup time or per-query overhead, by precomputing work
    3. The security of connection strings stored in config
    4. The number of migrations the project needs to keep

    Answer: B. Startup time or per-query overhead, by precomputing work Compiled models help large models start faster; compiled queries skip repeated LINQ translation in hot paths.

  10. Why do ORM lazy-loading proxies need virtual (C#) or non-final (Java/Kotlin) members?

    1. Proxies subclass the entity to intercept access, so members must be overridable
    2. The database requires virtual members to read column values from rows
    3. Virtual members are stored in a separate table from regular members
    4. Non-virtual members can't be serialized to JSON by any web framework

    Answer: A. Proxies subclass the entity to intercept access, so members must be overridable Kotlin needs the all-open plugin for JPA entities.

Practice all 261 questions

More Storage and Data