0% found this document useful (0 votes)
64 views11 pages

3.what Is The DbContext Class in EF Core

The DbContext class in Entity Framework Core represents a session with the database, allowing querying and saving of entity data. It provides object sets for entities, change tracking, database operations like save changes, and configuration of the database connection and models.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
64 views11 pages

3.what Is The DbContext Class in EF Core

The DbContext class in Entity Framework Core represents a session with the database, allowing querying and saving of entity data. It provides object sets for entities, change tracking, database operations like save changes, and configuration of the database connection and models.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 11

What is the DbContext Class in EF Core?

The DbContext class in Entity Framework Core is a crucial component that represents a session with
the database, allowing you to query and save instances of your entities. It acts as a bridge between
your domain or entity classes and the database, providing mechanisms to perform CRUD (Create,
Read, Update, Delete) operation.

DbContext in Entity Framework Core Performs the following tasks


Ad
 Ad

 Object Set Representation: DbContext represents a session with the


database that allows querying and saving of entity classes via
DbSet<TEntity> properties for each entity type in the model.

 Change Tracking: When retrieving data from the database using the
DbContext, the changes made to that data are tracked by the
DbContext. If any modifications, the entity’s properties are updated,
DbContext keeps track of those changes. This enables EF Core to
generate appropriate SQL statements to reflect the database changes
accurately.

 Database Operations: Using methods on DbContext, such as


SaveChanges(), we can insert, update, or delete records in the database.
That means the changes we make to our entities will be updated in the
database when we call the SaveChanges() method of the DbContext
object.

 Configuration: The DbContext allows for the configuration of the


database connection. It also tells how models are mapped to database
schemas, caching policies, etc. We need to do this by overriding the
OnConfiguring or OnModelCreating methods in our DbContext class (A
class that is inherited from the DbContext class).

 Querying: DbContext allows us to use LINQ to construct database


queries that are automatically translated into SQL queries based on the
database provided and will be executed on the corresponding database.
 Caching: Remember to use the DbContext to perform first-level caching
by default. This means that if you request the same data multiple times
while the DbContext instance is active, it will return the cached version
of the data instead of querying the database again. This can greatly
improve performance if you need to access the same data repeatedly.

 Connection Management: DbContext manages database connections,


i.e., it opens and closes the database connection as and when needed
and handles transactions for batch operations. Batch operation means
executing multiple SQL Statements.

 Migrations: The DbContext plays an important role in creating and


managing database migrations, which are a way to manage database
schema changes.

 Relationship Management: DbContext manages relationships (one-to-


one, one-to-many, and many-to-many) between entities and supports
navigation properties for foreign key relationships in the database.

 Database Provider Agnosticism: When using DbContext, your code will


be compatible with multiple databases (SQL Server, PostgreSQL, SQLite)
regardless of the specific database provider. So, our code will be the
same irrespective of the database provider and the backend database.
How to Create a DbContext Class in Entity Framework Core?

1. To use the DbContext class ,we must create a class derived from
the DbContext class.

2. The DbContext class is present


in Microsoft.EntityFrameworkCore namespace. The Entity Framework
Core DbContext class includes a property, i.e., DbSet<TEntity>, for each
entity in your application.

3. The DbSet is a collection of entity classes (i.e., entity set)

DbSet Properties: Inside your DbContext class, add DbSet<TEntity> properties for each entity type
you want to include in your model. These properties will represent tables in your database.

EXAMPLE:
public DbSet<Student> Students { get; set; }
public DbSet<Standard> Standards { get; set; }
Example
Have a look ?
The constructor public EFCoreDbContext() : base() is used to initialize an instance of the
EFCoreDbContext class by calling the constructor of the base class DbContext. This constructor is
typically used when you want to use the default constructor of the base class, which does not take
any parameters.

In Entity Framework Core, the DbContext class has several constructors, some of which accept
parameters such as DbContextOptions. When you use a constructor that accepts parameters, you
need to explicitly call the base class constructor with those parameters. However, if you want to use
the default constructor of the base class, you can simply call base() in your derived class constructor.

 In this example, MyDbContext is a derived class of DbContext that accepts an instance of


DbContextOptions<MyDbContext> in its constructor. This DbContextOptions instance is
then passed to the base class constructor using base(options) to configure the DbContext.

 Using a parameterized constructor allows you to customize the configuration of your


DbContext, such as specifying the database connection string and other options, making
your DbContext more flexible and configurable for different scenarios.
DbContext Properties in Entity Framework Core
1. ChangeTracker: Provides access to information and operations for entity instances that the
context is currently tracking.

2. Database: Provides access to database-related information and operations for this context.

3. Model: Returns the metadata about the shape of entities, the relationships between them,
and how they map to the database.

4. Options: Provides access to the options that were used to create the context.

5. Query: Provides access to LINQ queries against the database.

6. Set<TEntity>(): Returns a DbSet<TEntity> instance for access to entities of the given type in
the context.

7. Entity: Provides access to the underlying database-specific entities and relationships.

8. Entry(entity): Provides access to information and operations for a given entity being tracked
by the context.

9. Find<TEntity>(keyValues): Finds an entity with the given primary key values. If an entity with
the given primary key values is being tracked by the context, it is returned immediately
without making a request to the database. Otherwise, a query is made to the database for
an entity with the given primary key values, and it is returned if found.

10. Local: Gets a collection of all the entities that are currently being tracked by the context.

11. ChangeTracker.Entries(): Gets a collection of all the entities that are currently being tracked
by the context.

12. ChangeTracker.QueryTrackingBehavior: Gets or sets a value indicating how queries should


be tracked by the context.
13. ChangeTracker.AutoDetectChangesEnabled: Gets or sets a value indicating whether
DetectChanges is called automatically by methods of DbContext and related classes.

14. ChangeTracker.LazyLoadingEnabled: Gets or sets a value indicating whether navigation


properties for tracked entities should be loaded on access (lazy-loading).

15. Database.AutoTransactionsEnabled: Gets or sets a value indicating whether or not the


context automatically uses transactions.

16. Database.ProviderName: Gets the name of the database provider (e.g.,


"Microsoft.EntityFrameworkCore.SqlServer").
DbContext Methods in Entity Framework Core:
1. Add: Adds a new entity to DbContext with an Added state and starts
tracking it. This new entity data will be inserted into the database when
SaveChanges() is called.

2. AddAsync: Asynchronous method for adding a new entity to DbContext


with Added state and starts tracking it. This new entity data will be inserted
into the database when SaveChangesAsync() is called.

3. AddRange: Adds a collection of new entities to DbContext with Added state


and starts tracking it. This new entity data will be inserted into the database
when SaveChanges() is called.

4. AddRangeAsync: Asynchronous method for adding a collection of new


entities, which will be saved on SaveChangesAsync().

5. Attach: Attaches a new or existing entity to DbContext with an Unchanged


state and starts tracking it. In this case, nothing will happen when we call
the SaveChanges method, as the entity state is not modified.

6. AttachRange: Attaches a collection of new or existing entities to DbContext


with an Unchanged state and starts tracking it. In this case, nothing will
happen when we call the SaveChanges method, as the entity state is not
modified.

7. Entry: Gets an EntityEntry for the given entity. The entry provides access to
change tracking information and operations for the entity. So, using this
method, we can manually set the Entity State, which DbContext will also
track.

8. Find: Find an entity with the given primary key values.

9. FindAsync: Asynchronous method for finding an entity with the given


primary key values.

10.Remove: It sets the Deleted state to the specified entity, which will delete
the data when SaveChanges() is called.
11.RemoveRange: Sets Deleted state to a collection of entities that will delete
the data in a single DB round trip when SaveChanges() is called.

12.SaveChanges: Execute INSERT, UPDATE, or DELETE commands to the


database for the entities with Added, Modified, or Deleted state.

13.SaveChangesAsync: Asynchronous method of SaveChanges()

14.Set: Creates a DbSet<TEntity> that can be used to query and save instances
of TEntity.

15.Update: Attaches disconnected entity with Modified state and starts


tracking it. The data will be saved when SaveChagnes() is called.

16.UpdateRange: Attaches a collection of disconnected entities with a


Modified state and starts tracking it. The data will be saved when
SaveChagnes() is called.

17.OnConfiguring: Override this method to configure the database (and other


options) for this context. This method is called for each instance of the
context that is created.

18.OnModelCreating: Override this method to configure further the model


discovered by convention from the entity types exposed in DbSet<TEntity>
properties on your derived context.
Note:

The DBContext is the heart of the Entity Framework Core. It is the


connection between our entity classes and the database. The
DBContext is responsible for database interactions like querying the
database and loading the data into memory as an entity. It also tracks
the changes made to the entity and persists the changes to the
database.

You might also like