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();
}
About the author
- Bug & Fix is where AI concepts meet real-world software engineering. We break down modern development, intelligent systems, tools, architecture, and emerging technologies into practical insights for developers who want to build better software and stay ahead.
Comments
Join the discussionNo comments yet. Be the first to comment.




