DEV Community

Cover image for Delete in EF 8 !
Bug & Fix
Bug & Fix

Posted on

Delete in EF 8 !

Deleting a record efficiently using Entity Framework (EF) involves a few key considerations to minimize unnecessary database operations and improve performance.


public async void DeleteStudent(int Id)
{
        UniverSityDBContext db = new UniverSityDBContext();
        var studentData = db.Students.FindAsync(Id).Result;                
        if (studentData == null)
            throw new Exception("Student not found");

        db.Students.Remove(studentData);
        await db.SaveChangesAsync();
}
//
public void DeleteStudentOptimized(int Id)
{
    UniverSityDBContext db = new UniverSityDBContext();
    var student = new Student { ID = Id };
    var studentEntity = db.Students.Attach(student);
    studentEntity.State = EntityState.Deleted;
    db.SaveChanges();
}
Enter fullscreen mode Exit fullscreen mode

Top comments (0)