Code and prod logo

Code and Prod Complet Projects

Follow me

EL JIHAOUI
QUICK ACCESS

DbContext And DbSet .NET7

DbContext and DbSet in EF Core

Table of Contents

In .Net7, DbContext, and DbSet are the most used classes when working with the Entity Framework Core. We can use these two classes to easily perform CRUD operations.

Logically, DBContext maps to a specific database, and each DbSet will map to a table in this database.

DbContext

DbContext

DbContext: is the primary class that is responsible for interacting with the database, so he can do the following actions:

  • Manage the database connection
  • Perform CRUD operation

DbContext  is also responsible for the following activities :

  • Manage database connection: In order to connect to a database, we need the database connection string
  • Querying : Converts LINQ-to-Entities queries to SQL queries and sends them to the database.
  • Change Tracking : Keeps track of changes that occurred on the entities after querying from the database.
  • Persisting Data: Performs the Insert, Update, and Delete operations to the database, based on entity states.
  • Caching: Provides first-level caching by default. It stores the entities which have been retrieved during the lifetime of a context class.
  • Manage Relationship: Manages relationships in Db-First or Model-First approach.
  • Object Materialization: Converts raw data from the database into entity objects

The DbContext class is typically responsible for interacting with data as objects. The recommended way to work with context is to define a class that derives from the DbContext and exposes the DbSet properties that represent collections of entities in the context.

Example of a class that uses or inherits from the DbContetxt class :

				
					public class AppDbContext : DbContext
    {
        protected override void OnConfiguring(DbContextOptionsBuilder options)
        {
            options.UseSqlServer(@"Server=.\SQLEXPRESS; Database=EFCoreDb;
                   Trusted_Connection=True;Encrypt=False;");
        }
        public DbSet<Book>? Books { get; set; }
        public DbSet<Category>? Categories { get; set; }
        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            modelBuilder.Entity<Category>().HasData(
             new Category {Id=1, Name = "Web" },
             new Category {Id=2, Name = "Development" },
             new Category {Id=3, Name = "Design" },
             new Category {Id=4, Name = "Marketing" }
            );
        }
    }
				
			

AppDbContext Inherit from the DbContext class which is in Miscrosoft.Data.Entity namespace

the OnConfiguring() method enables us to choose and set up the data source to be utilized with a context using DbContextOptionsBuilder.

The OnModelCreating() method allows us to configure the model using ModelBuilder.

ConnectionString

In the DbContext class, we need to define the type of the database (SQL Server, MySQL, Oracle, etc…) and the ConnectionString used to connect to our database.

For this reason, we will override the OnConfiguring function and then add the following instruction :

				
					protected override void OnConfiguring(DbContextOptionsBuilder options)
{
 options.UseSqlServer(@"Server=.\SQLEXPRESS; Database=EFCoreDb;Trusted_Connection=True;Encrypt=False;");
}
				
			

connection string  is a string that specifies information about a data source. The connection string may include attributes such as the name of the driver, server, and database, as well as security information such as user name and password.

DbContext Properties

#PropertyDescription
1ChangeTrackerProvides access to features of the context that deal with change tracking of entities.
2ConfigurationProvides access to configuration options for the context.
3DatabaseCreates a Database instance for this context that allows for creation/deletion/existence checks for the underlying database.

DbContext Methods

MethodDescription
Dispose()Calls the protected Dispose method.
Dispose(Boolean)Disposes of the context.
Entry(Object)Gets a DbEntityEntry object for the given entity providing access to information about the entity and the ability to perform actions on the entity.
Entry<TEntity>(TEntity)Gets a DbEntityEntry<TEntity> object for the given entity providing access to information about the entity and the ability to perform actions on the entity.
Equals(Object)Determines whether the specified object is equal to the current object.
GetHashCode()Serves as the default hash function.
GetType()Gets the Type of the current instance.
GetValidationErrors()Validates tracked entities and returns a Collection of DbEntityValidationResult containing validation results.
OnModelCreating(DbModelBuilder)This method is called when the model for a derived context has been initialized, but before the model has been locked down and used to initialize the context. The default implementation of this method does nothing, but it can be overridden in a derived class such that the model can be further configured before it is locked down.
SaveChanges()Saves all changes made in this context to the underlying database.
SaveChangesAsync()Asynchronously saves all changes made in this context to the underlying database.
Set(Type)Returns a non-generic DbSet instance for access to entities of the given type in the context and the underlying store.
Set<TEntity>()Returns a DbSet<TEntity> instance for access to entities of the given type in the context and the underlying store.
ShouldValidateEntity(DbEntityEntry)Extension point allowing the user to override the default behavior of validating only added and modified entities.
ToString()Returns a string that represents the current object.
ValidateEntity(DbEntityEntry, IDictionary<Object,Object>)Extension point allowing the user to customize validation of an entity or filter out validation results. Called by GetValidationErrors().

DbSet

DbSet

In the DbContext class, you can create properties that are type DbSet<T>. The generic type parameter T will be a type of entity like Book is an entity in our application.

The DbSet class represents an entity set that can be used for createreadupdate, and delete operations.

DbSet Methods

MethodDescription
Add(Object)Adds the given entity to the context underlying the set in the Added state such that it will be inserted into the database when SaveChanges is called.
AddRange(IEnumerable)Adds the given collection of entities into context underlying the set with each entity being put into the Added state such that it will be inserted into the database when SaveChanges is called.
AsNoTracking()Returns a new query where the entities returned will not be cached in the DbContext.(Inherited from DbQuery)
Attach(Object)Attaches the given entity to the context underlying the set. That is, the entity is placed into the context in the Unchanged state, just as if it had been read from the database.
Cast<TEntity>()Returns the equivalent generic DbSet<TEntity> object.
Create()Creates a new instance of an entity for the type of this set.
Create(Type)Creates a new instance of an entity for the type of this set or for a type derived from the type of this set.
Equals(Object)Determines whether the specified object is equal to the current object.
Find(Object[])Finds an entity with the given primary key values.
FindAsync(CancellationToken, Object[])Asynchronously finds an entity with the given primary key values.
FindAsync(Object[])Asynchronously finds an entity with the given primary key values.
GetHashCode()Serves as the default hash function.
GetType()Gets the Type of the current instance.
Include(String)Specifies the related objects to include in the query results. (Inherited from DbQuery)
Remove(Object)Marks the given entity as Deleted such that it will be deleted from the database when SaveChanges is called.
RemoveRange(IEnumerable)Removes the given collection of entities from the context underlying the set with each entity being put into the Deleted state such that it will be deleted from the database when SaveChanges is called.
SqlQuery(String, Object[])Creates a raw SQL query that will return entities in this set.
ToString()Returns a String representation of the underlying query. (Inherited from DbQuery)

Course video

if you like it share it please

Facebook
LinkedIn
Twitter
Related Posts
Data Seeding in migration using EF Core
Entity Framework Core
EL JIHAOUI

Data seeding

Data seeding is a process where you populate a database with an initial set of data
There are

Read More »

MORE RESSOURCES