Loading

Microsoft Entity Framework

What is DbSet in Entity Framework Database First Approach?. The Complete Microsoft Entity Framework Developer Course 2023 [Videos].

In this article, I am going to discuss DbSet class in Entity Framework Database First Approach with Examples. Please read our previous article where we discussed DbContext in Entity Framework. At the end of this article, you will understand the need and use of Entity Framework DbSet in detail.

Note: We are going to work with the same example that we created in our Introduction to Entity Framework Database First Video. Please read our introduction to Entity Framework Database First Video before proceeding to this Video.

DbSet in Entity Framework

The DbSet class in Entity Framework represents an entity set that can be used for the database CRUD Operations i.e. create, read, update, and delete operations. The context class should derive from DbContext class and must include the DbSet type properties for the entities which map to database tables and views. The DbSet in Entity Framework is actually an implementation of the Repository pattern.

Example to Understand DbSet in Entity Framework with Examples:

As we already discussed in our previous Video, the Entity Framework creates the following Context class for us. As you can see in the below image, for each database table and view, the entity framework creates DbSet properties.

DbSet in Entity Framework Database First Approach

Note: A DbSet represents the collection of all entities in the context, or that can be queried from the database, of a given type. DbSet objects are created from a DbContext using the DbContext.Set method. The DbSet does not support MEST (Multiple Entity Sets per Type) meaning that there is always a one-to-one correlation between a type and a set.

Methods of DbSet:

The Entity Framework DbSet provides some methods using which we can perform different types of operations. Let us understand some of the commonly used methods of DbSet.

DbSet Add Method in Entity Framework:

The DbSet Add method is used to add the given entity to the context with the Added State. When the changes are saved (i.e. when the SaveChanges method is called), the entity which is in the Added state is inserted into the database. Once the changes are saved into the database, the object state changes to Unchanged.

Example: For a better understanding of the DbSet Add method, please have a look at the below image. Here, we are creating a student object and then passing that student object to the Add method (now the entity in Added State), and then we are calling the SaveChanges() method (entity state change to Unchanged state).

DbSet Add Method

DbSet AddRange Method in Entity Framework:

The DbSet AddRange method is used to add a given collection of entities to the context with the Added State. When the changes are saved (i.e. when the SaveChanges method is called on the Context object), all the entities which are in the Added state are inserted into the database table. Once the changes are saved into the database, the object states are changes to Unchanged.

Example: For a better understanding of how to use the AddRange method, please have a look at the below image. Here, first, we created a list of Student objects. Then we pass this list of student objects (i.e. students) to the AddRange method and then we are calling the SaveChanges() method.

DbSet AddRange Method

Note: If System.Data.Entity.Infrastructure.DbContextConfiguration.AutoDetectChangesEnabled is set to true (which is the default), then DetectChanges will be called once before adding any entities and will not be called again. This means that in some situations AddRange may perform significantly better than calling Add multiple times. 

DbSet Attach Method in Entity Framework:

This method is used to attach the given entity to the context object with the Unchanged state. That means calling the SaveChanges method on the context object will not affect the database.

Example: For a better understanding of the Attach method, please have a look at the below image. Here, first, we create a student object. Then we pass the student object to the Attach method. The attach method will change the state of the entity to Unchanged and then we call the SaveChanges method which does not affect the database. 

DbSet Attach Method

DbSet AsNoTracking Method in Entity Framework:

It is an extension method where the returned entities will not be tracked by the DBContext. This will be a significant performance boost for read-only entities. This method returns a new query where the entities returned will not be cached in the System.Data.Entity.DbContext. That means a new query with NoTracking applied will be returned from this method. For better understanding please have a look at the below image. Here, we are returning a list of students using the AsNoTracking method. This list of students will not be tracked by the DbContext class which improves the performance. In this case, the entities are going to be in Detached State.

DbSet AsNoTracking Method

DbSet Create Method in Entity Framework:

This method is used to create and return a new instance of an entity. This entity is not added or attached to the set. Here, the entity will be created with the default values. For better understanding, please have a look at the below image. Here, the entity created is going to be in Detached State.

DbSet Create Method

DbSet Include Method in Entity Framework:

The SbSet Include method is used to specifies the related objects to include in the query results. That means it returns the included non-generic LINQ to Entities query against a DbContext. For better understanding, please have a look at the below image. In the below query, it will return the student list along with their address.

DbSet Include Method

Note: Paths are all-inclusive. For example, if an include call indicates Include(“Orders.OrderLines”), not only the OrderLines are included, but also Orders are included. When you call the Include method, the query path is only valid on the returned instance of the DbQuery<T>. Other instances of DbQuery<T> and the object context itself are not affected. Because the Include method returns the query object, you can call this method multiple times on a DbQuery<T> to specify multiple paths for the query.

DbSet Find Method in Entity Framework:

This method is used to Find and return an entity with the given primary key values. If an entity with the given primary key values exists in the context, then it is returned immediately without making a request to the database. Otherwise, a request is made to the database for an entity with the given primary key values and this entity, if found, is attached to the context and returned. If no entity is found in the context or in the database, then null is returned. For better understanding, please have a look at the below image.

DbSet Find Method

Note: The point that you need to remember is that Find also returns the entities that have been added to the context but have not yet been saved to the database.

DbSet Remove Method in Entity Framework:

The DbSet Remove method is used to remove or delete an entity from the database. The point that you need to keep in mind is the entity is not removed immediately rather the entity state will be marked as deleted. As soon as the SaveChanges method is called on the Context object, the entity is deleted from the database. The entity must exist in the context in some other state before this method is called. For better understanding, please have a look at the below image.

DbSet Remove Method

DbSet RemoveRange Method in Entity Framework:

The DbSet RemoveRange method is used to remove or delete a collection of entities from the database. Like the Remove method, when the RemoveRange method is called the entities are not removed immediately rather the entitys states will be marked as deleted. As soon as the SaveChanges method is called on the Context object, the context will delete the entities from the database. For better understanding, please have a look at the below image.

DbSet RemoveRange Method

Note: If System.Data.Entity.Infrastructure.DbContextConfiguration.AutoDetectChangesEnabled is set to true (which is the default), then DetectChanges will be called once before deleting any entities and will not be called again. This means that in some situations RemoveRange may perform significantly better than calling Remove multiple times would do. Note that if any entity exists in the context in the Added state, then this method will cause it to be detached from the context. This is because an Added entity is assumed not to exist in the database such that trying to delete it does not make sense.

DbSet SqlQuery Method in Entity Framework:

This DbSet SqlQuery method in Entity Framework creates a raw SQL query that will return entities. By default, the entities returned are tracked by the context; this can be changed by calling the AsNoTracking method. It has two parameters. The First Parameter is the SQL query string and the second is the parameters to apply to the SQL query. For better understanding, please have a look at the below image.

DbSet SqlQuery Method

Note: In our upcoming Videos of this series, we will discuss the need and importance of each method in detail with real-time examples.

See All

Comments (440 Comments)

Submit Your Comment

See All Posts

Related Posts

Microsoft Entity Framework / Audio Video

How we can install sql server and create db?

How we can install sql server and create db?
24-aug-2024 /37 /440

Microsoft Entity Framework / Blog

What is the Entity Framework?

Entity Framework is an Open-Source Object-Relational Mapping (ORM) Framework for .NET applications that enables .NET developers to work with relational data using domain-specific objects without focusing on the underlying database tables and columns where actually the data is stored. That means the Entity Framework eliminates the need for writing the data-access code that developers usually need to write.
11-Feb-2022 /37 /440

Microsoft Entity Framework / Blog

What is Entity Framework Architecture?

In this article, I am going to discuss the Entity Framework Architecture in Detail. Please read our previous article where we discussed the Overview of the Entity Framework. At the end of this article, you will understand the following pointers in detail.
11-Feb-2022 /37 /440