Entity Framework dbset the most efficient way to remove

I have the following and are looking for a more efficient way to delete vs looping records and then deleting each one at a time (note using Dbset):

var wcd = dbContext.ProgramDetails.Where(p => p.Id == Id); foreach (var wc in wcd.ToList()) { dbContext.ProgramDetails.Remove(wc); } dbContext.SaveChanges(); 

Also tell me if we have 1 entry, the following:

  var pg = dbContext.Program.Where(p => p.Id == Id && Name == FName); 

What is the best way to delete this entry?

tried the following but gave an error:

  var pg = dbContext.Program.Where(p => p.Id == Id && Name == FName); dbContext.Program.Remove(wc); 

Then I resorted to doing foreach to delete only one record, as I showed above, which is not the most effective for only 1 record.

+8
linq entity-framework
source share
1 answer

UPDATE FOR EF7 :

 using (var db = new BloggingContext()) { var blog = db.Blogs.First(p => p.Id == Id); db.Remove(blog); db.SaveChanges(); } 

UPDATE MAY 2015 . Check updated msdn docs and examples . Sample code for deleting an object with EF6:

  public async Task<ActionResult> Delete(Department department) { try { db.Entry(department).State = EntityState.Deleted; await db.SaveChangesAsync(); return RedirectToAction("Index"); } catch (DbUpdateConcurrencyException) { return RedirectToAction("Delete", new { concurrencyError = true, id = department.DepartmentID }); } catch (DataException /* dex */) { //Log the error (uncomment dex variable name after DataException and add a line here to write a log. ModelState.AddModelError(string.Empty, "Unable to delete. Try again, and if the problem persists contact your system administrator."); return View(department); } } 

The most efficient way if you know the identifier and don’t load the object is to create a fake object and delete it

 var p = new Program { Id = myId } dbContext.Program.Remove(p) 

But this will not work if you really have several records with the same identifier, and you need to use the name field, and also select the correct one.

Also your last example should be

 var pg = dbContext.Program.First(p => p.Id == Id && p.Name == FName); dbContext.Program.Remove(pg); 
+8
source share

All Articles