Here we learn how to delete data from database in entity framework core, delete record by id and bulk delete or batch delete.
How Delete works in EF Core!
As I said in earlier tutorial that EF Core API can keep track of all the entities retrieved using the context,
so when you delete or remove any data from context object and finally call the SaveChanges()
method, all new changes made to context gets saved to database, thus data gets deleted from database also.
In entity framework core the delete method is replaced with remove();
Here is an example of deleting single row by id using DbContext object.
public bool DeleteStudent(int stuid) { bool _isDeleted = false; Student _s = null; var context = new EFContext(); _s = context.tbStudent .Where(s=>s.StuId==stuid) .FirstOrDefault<Student>(); if (_s != null) { context.tbStudent.Remove(_s); context.SaveChanges(); _isDeleted = true; } return _isDeleted; }
Once the Remove()
method is executed for the Student entity, the EF marks that particular data as Deleted. Finally when the SaveChanges() method is called, data gets deleted from database.
Deleting multiple rows at a time is very simple in entity framework core, Deleting multiple rows at a time is very simple in entity framework core, there is a built-in method called RemoveRange, which takes a list object as parameter, means all matching data will be removed and finally deleted from database
Let's say we want to delete students where student id is 1, 3, 5, Here is the code below
using (WTRDBContext context = new WTRDBContext()) { List<tbstudent> students = new List<tbstudent>() { new tbStudent(){StuId=1}, new tbStudent(){StuId=3}, new tbStudent(){StuId=5} }; context.Students.RemoveRange(students); context.SaveChanges(); }
Notice, how to call the RemoveRange(students)
method with object list.
Note: while specifying any data to be deleted, the data should be there in database, means data id you provide in query must match with data in database, otherwise EF Core will thrown exception of type DbUpdateConcurrencyException.