Free Web Development Online Tutorials, Learn to Code
Learn Entity Framework with C#, Entity Framework Core, Code First, DB First Approach

Delete method in Entity Framework Core

Here we learn how to delete data using entity framework core

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();

Deleting single row in EF Core

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 using EF Core DBContext

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();
}

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.


Comment
Name
Email
Website
Subscribe
 
Delete example in EF Core