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