DbSet in Entity Framework Database First Approach
In this article, I am going to discuss DbSet class in Entity Framework Database First Approach. 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 article. Please read our introduction to Entity Framework Database First article before proceeding to this article.
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:
As we already discussed in our previous article, 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.
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:
This 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 Add method, please have a look at the below image.
DbSet AddRange Method:
This 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), 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.
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 would do. Note that entities that are already in the context in some other state will have their state set to Added. AddRange is a no-op for entities that are already in the context in the Added state.
DbSet Attach Method:
This method is used to attach the given entity to the context object with the Unchanged. 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.
DbSet AsNoTracking Method:
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.
DbSet Create Method:
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.
DbSet Include Method:
This 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.
Note: Paths are all-inclusive. For example, if an include call indicates Include(“Orders.OrderLines”), not only will OrderLines be included, but also Orders. 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:
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.
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:
The Remove method is used to remove or delete the 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 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.
DbSet RemoveRange Method:
The 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 entity’s 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.
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:
This method 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.
Note: In our upcoming articles of this series, we will discuss the need and importance of each method in detail with real-time examples.
In the next article, I am going to discuss the Entity Framework Relationship in detail. In this article, I try to explain the DbSet in Entity Framework Database First Approach and I hope you enjoyed DbSet in Entity Framework article. Please give your valuable feedback and suggestions about this article.