Home

DbContext

DbContext is a primary class in Entity Framework (EF) that represents a session with a database and provides the API used to query and save instances of entity classes. In EF Core, applications define a derived class from DbContext with a set of properties of type DbSet<TEntity> that expose the entities you want to query or save.

The context tracks changes to retrieved entities via a change tracker, enabling updates, inserts, and deletes

Contexts are configured with DbContextOptions, which specify the database provider, connection string, and other behaviors. A

DbSet properties map to tables; LINQ queries are translated to SQL. EF Core supports features such as

As a gateway to data, DbContext is the unit of work and uses DbSet to perform CRUD

to
be
persisted
back
to
the
database
when
SaveChanges
or
SaveChangesAsync
is
called.
It
also
coordinates
relationships
among
entities
and
performs
identity
resolution
so
multiple
queries
return
the
same
CLR
instance
for
the
same
row.
context
is
typically
created
per
unit
of
work
or
per
request
and
disposed
when
the
operation
completes.
It
can
be
used
with
dependency
injection
in
modern
apps.
change
tracking,
lazy
loading
(via
proxies),
explicit
loading,
transactions,
migrations,
and
query
tracking
modes.
operations.
It
relies
on
conventions,
data
annotations,
and
the
Fluent
API
to
configure
the
model.
The
context
plays
a
central
role
in
the
data
access
layer,
coordinating
query
construction,
change
tracking,
and
persistence
across
the
application's
data
access
code.