The Entity Framework Core
DbContext class represents a session with a database and provides an API for communicating with the database with the following capabilities:
- Database Connections
- Data operations such as querying and persistance
- Change Tracking
- Model building
- Data Mapping
- Object caching
- Transaction management
The DbContext is responsible for opening and managing connections to the database.
The DbContext provides methods for performing the following data operations directly.
The DbContext also provide data querying capability via the DbSet property.
The Change Tracker detects changes made to entities and sets the
EntityState of an object accordingly. The state of the entity determines the type of operation that the database will be asked to perform upon it, and therefore the SQL that will be generated.
DbContext builds a conceptual model based on convention and configuration, and maps that to the database. The model and its mappings are built at application startup and are persisted in memory for the lifetime of the application.
DbContext includes a data mapper layer responsible for mapping the results of SQL queries to entity instances and other types defined by the client application.
The DbContext provides a first-level cache for objects that it is asked to retrieve from the data store. Subsequent requests for the same object will return the cached object instead of executing another database request.
When the DbContext
SaveChanges method is called, a transaction is created and all pending changes are wrapped in it as a single unit of work. If an error occurs when the changes are applied to the database, they are rolled back and the database is left in an unmodified condition.