The DbSet represents the collection of all entities in the context. Every model must expose the DbSet property to become part of the Context and managed by it. We use the DbSet to query, insert, update & Delete entities. In this tutorial, we will look into DbSet and its methods in detail.
Table of Contents
Modeling the Database
In EF Core we create POCO Classes to represent our database. Each table in the database, will gets its own class. For Example, the Product Table in the database can be represented using the following class. Here id
& name
represents the columns in the table.
1 2 3 4 5 6 7 | public class Product { public int Id { get; set; } public string Name { get; set; } } |
It is a simple POCO class. The EF Core knows nothing about the class. It will not be included in the model and will not be mapped to the database.
DbSet
To Include the above class in the model, we must define a DbSet property of the class. The DbSet property must be included in the Context class.
1 2 3 4 | public DbSet<Product> Products { get; set; } |
Typical Context class is as shown below. This is the Context class we used in the Entity Framework Core Console Application tutorial.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | public class EFContext : DbContext { private const string connectionString = "Server=(localdb)\\mssqllocaldb;Database=EFCore;Trusted_Connection=True;"; protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder) { optionsBuilder.UseSqlServer(connectionString); } public DbSet<Product> Products { get; set; } } |
We need to create DbSet
Property for each & every class, which we want to be part of the model.
EF Core scans all the types, which have a DbSet property and includes them in the model. It also looks for the public properties & types and uses it to determine the columns & types. We can also provide extra modeling information using conventions, data annotation attributes, & Fluent API.
The DBSet
Provides methods like Add
, Attach
, remove
, etc on the Entity Types. The Context class maps these operations into a SQL query and runs it against the database using the Database Providers.
DbSet Implements the IQueryable & IEnumerable interfaces This allows us to query the database using the LINQ query.
Using DbSet
The following are few of the examples on how to use DbSet.
Adding Single Record
The Add method adds the given entity to the context in the Added state. The EF Core generates the insert SQL query and updates the database when we call the SaveChanges
method.
Syntax
1 2 3 4 | Add(TEntity) AddAsync(TEntity, CancellationToken) |
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 | using (EFCoreContext db = new EFCoreContext()) { Department department = new Department(); department.Name = "Secuirty"; db.Departments.Add(department); //Adding to the Context db.SaveChanges(); //Saving Changes to database } |
Read more from Add Single Record in EF Core
Adding Multiple Records
This AddRange
method adds the collection of entities to the context. All the entities in the collection are marked as Added State. All the entities are inserted into the database table when saved by the context (by Calling SaveChanges
method)
Note that entities that are already in the context in some other state will have their state set to Added
Syntax
1 2 3 4 5 6 7 8 9 | AddRange(IEnumerable<TEntity>) AddRange(TEntity[]) AddRangeAsync(IEnumerable<TEntity>, CancellationToken) AddRangeAsync(TEntity[]) |
Example
1 2 3 4 5 6 7 8 9 10 11 12 | using (EFCoreContext db = new EFCoreContext()) { List<Department> deps = new List<Department>(); deps.Add(new Department { Name = "Dept1", Descr = "" }); deps.Add(new Department { Name = "Dept2", Descr = "" }); db.Departments.AddRange(deps); db.SaveChanges(); } |
Read more from Add Multiple Records in EF Core
Attaching Records
The Attach method attaches the given entity to the context. The records are marked as Unchanged. It means calling savechanges
on the context will have no effect on the database
1 2 3 4 5 | Attach(TEntity) AttachRange(IEnumerable<TEntity>) AttachRange(TEntity[]) |
Finding an Entity
EF Core Find
method finds a record with the given primary key values. If the entity is already in the context (because of a previous query), then the Find
method returns it. The Find
method sends the query to the database if it does not find it in the context.
Syntax
1 2 3 4 5 | Find(Object[]) FindAsync(Object[]) FindAsync(Object[], CancellationToken) |
Example
1 2 3 4 5 6 7 8 9 10 11 12 | using (EFCoreContext db = new EFCoreContext()) { var Department= db.Department.Find(1); if (Department!=null) { Console.WriteLine(Department.Name); } } |
Read more Find method in EF Core
Update a Single Record
To Update the entity, First, we query and get the entity from the database, make the necessary changes, and then call the SaveChanges
to persist the changes in the database.
Example
1 2 3 4 5 6 7 8 9 10 11 | using (EFCoreContext db = new EFCoreContext()) { department = db.Departments.Where(d => d.Name == "Sales").First(); department.Descr = "This is Sales Department"; db.SaveChanges(); Console.WriteLine("Department {0} ({1}) is Updated ", department.Name, department.DepartmentID); } |
Update Multiple Records
Similarly, query multiple records from the database, update the records and call the saveChanges
.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | private void UpdateMultipleRecords() { List<Department> departments = new List<Department>(); departments.Add(new Department { DepartmentID = 1, Descr = "Sales" }); departments.Add(new Department { DepartmentID = 2, Descr = "Purchase" }); departments.Add(new Department { DepartmentID = 3, Descr = "HR" }); using (EFCoreContext db = new EFCoreContext()) { foreach (var item in departments) { var dept = db.Departments.Where(f => f.DepartmentID == item.DepartmentID).FirstOrDefault(); if (dept == null) throw new Exception(""); dept.Descr = item.Descr; } db.SaveChanges(); } } |
Read more from Update/Modify Records in EF Core
Deleting a Single Record
Remove method is used to delete the entity from the database. The entity is not deleted immediately. They are marked as deleted. The entity is deleted from the database when SaveChanges
is called.
Syntax
1 2 3 | Remove(TEntity) |
Example
1 2 3 4 5 6 7 8 | using (EFCoreContext db = new EFCoreContext()) { department = db.Departments.Where(d => d.Name == "Sales").First(); db.Departments.Remove(department); db.SaveChanges(); } |
Deleting a Multiple Record
RemoveRange
method used to delete the collection of entities. It does so by changing the state of entities to the deleted state. When the SaveChanges
method is invoked, Context will delete these entities from the database
Syntax
1 2 3 4 | RemoveRange(IEnumerable<TEntity>) RemoveRange(TEntity[]) |
Example
1 2 3 4 5 6 7 8 | using (EFCoreContext db = new EFCoreContext()) { List<Department> deps = db.Departments.Take(2).ToList(); db.Departments.RemoveRange(deps); db.SaveChanges(); } |
Read more from Delete Records in EF Core
Reference
Read More
- Entity Framework Core Tutorial
- ASP.NET Core Tutorial
- Querying in Entity Framework Core
- First, FirstOrDefault, Single, SingleOrDefault in EF Core
- EF Core Find Method
- Save Changes in Entity Framework Core
- ChangeTracker, EntityEntry & Entity States
- Add Records/Add Multiple Records
- Update Record
- Delete Record
- Cascade Delete in Entity Framework Core