Learn how to delete records from the database using Entity Framework. Deleting an entity is done using the Remove
or RemoveRange
method of the DbSet. Alternatively, you can also set the entity state
as Deleted
. We can delete records either in connected or disconnected Scenarios. We will also look at how to remove multiple records from the database using the RemoveRange
method.
Source Code:
The source code of this project available in GitHub.
You can refer to our following tutorial on
- Persistence in Entity Framework
- The Entity States in Entity Framework
- Add Record Entity Framework
- Update Record in Entity Framework
Table of Contents
Delete a Record
How you delete the entity depends on whether you are deleting the record in Connected or Disconnected scenario. In Connected Scenario, you can use the Remove
or RemoveRange
method to mark the record as Deleted
. In Disconnected Scenario, you can attach it to the context and set its state as Deleted
. Calling SaveChanges
will send the delete query to the database.
Connected Scenario
Deleting in a connected scenario is very straight forward. Query the Department
entity from the database. Call Remove
method and pass the Department
object to delete. The Change tracking in Entity Framework marks the entity as Deleted
. Finally, SaveChanges
will remove the Department
from the database using the Delete
Query
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 | Department dep; //Connected Scenario using (EFContext db = new EFContext()) { db.Database.Log = Console.WriteLine; dep = db.Departments.Where(d => d.Name == "Accounts").First(); db.Departments.Remove(dep); db.SaveChanges(); Console.WriteLine("Department {0} ({1}) is Deleted ", dep.Name, dep.DepartmentID); Console.ReadKey(); } |
SQL Query
1 2 3 4 | DELETE [dbo].[Departments] WHERE ([DepartmentID] = @0) |
Disconnected Scenario
The following is the disconnected scenario example. First, we retrieve the Department
entity and close the context. Later we open a new context and use the db.Entry
method to set its state as Deleted
. If the model is not in the context, then the Entry
method adds it to the context and sets its state as Deleted
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | Department dep; //Disconnected Scenario using (EFContext db = new EFContext()) { db.Database.Log = Console.WriteLine; dep = db.Departments.Where(d => d.Name == "Production").First(); } using (EFContext db = new EFContext()) { db.Database.Log = Console.WriteLine; db.Entry(dep).State = System.Data.Entity.EntityState.Deleted; db.SaveChanges(); } |
Attach Method
You can also use the Attach
and remove
method as shown below. Note that Attach
will add the entity to the context in Unchanged
state.
1 2 3 4 | db.Departments.Attach(dep); db.Entry(dep).State = System.Data.Entity.EntityState.Deleted; |
Deleting without loading from the database
You can delete the entity without loading from the database, provided you know the Primary key. The following example shows how to delete without loading from the database. We create a new department entity and assign the 2 to DepartmentID
. Next, we attach it to the context and set its state as Deleted
. On SaveChanges
the EF will delete the Department
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 | public void DeleteDisconnectedWithoutLoading() { Department dep; dep = new Department() { DepartmentID = 2 }; using (EFContext db = new EFContext()) { db.Database.Log = Console.WriteLine; db.Entry(dep).State = System.Data.Entity.EntityState.Deleted; db.SaveChanges(); } Console.WriteLine("Department {0} is Deleted ", dep.DepartmentID); Console.ReadKey(); } |
Delete & ConcurrencyCheck
The above code will not work if you have enabled ConcurrencyCheck on the table. For example open the Department
model and add the ConcurrencyCheck
on the Name
property as shown below.
1 2 3 4 5 6 7 8 9 10 11 12 | public class Department { public int DepartmentID { get; set; } [ConcurrencyCheck] public string Name { get; set; } public string Descr { get; set; } public virtual ICollection<Employee> Employees { get; set; } } |
Run the above code again and you will see the following exepction
System.Data.Entity.Infrastructure.DbUpdateConcurrencyException' occurred in EntityFramework.dll
Deleting Multiple Records
You can use RemoveRange
method of DbSet
to remove multiple records at a time. The following example code deletes 3 departments
from the database in the connected scenario.
The EF sends one delete query at time to the database. So if you delete 100 records, the EF will issue 100 delete statements
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | public void DeleteMultipleRecordsConnected() { //Deleting Multiple Records using (EFContext db = new EFContext()) { db.Database.Log = Console.WriteLine; List<Department> deps = db.Departments.Take(2).ToList(); db.Departments.RemoveRange(deps); try { db.SaveChanges(); } catch (Exception e) { Console.WriteLine(e.Message); } } Console.ReadKey(); } |
The following code deletes the multiple records in disconnected scenario.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 | public void DeleteMultipleRecordsDisconnected() { List<Department> deps = new List<Department>(); deps.Add(new Department { DepartmentID = 1 }); deps.Add(new Department { DepartmentID = 2 }); //Deleting Multiple Records using (EFContext db = new EFContext()) { db.Database.Log = Console.WriteLine; db.Entry(deps).State= System.Data.Entity.EntityState.Deleted; try { db.SaveChanges(); } catch (Exception e) { Console.WriteLine(e.Message); } } Console.ReadKey(); } |
Reference
Read More