Delete in EF 8 !
Bug And Fix
1 min read
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();
}
0
Subscribe to my newsletter
Read articles from Bug And Fix directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
Bug And Fix
Bug And Fix
Software development especially the .NET stack is our hobby, but we talk about everything related to technology..