Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Entity Framework dbset most efficient way of deleting

I have the following and looking for a more efficient way of deleting vs looping through the 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 say if we have 1 record that is as following:

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

What is the best way of deleting this one record?

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 a foreach for deleting just one record as I have shown above that is not the most efficient for just 1 record.

like image 914
Nate Pet Avatar asked Oct 11 '12 02:10

Nate Pet


1 Answers

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 docs on msdn and examples . Example code to delete entity 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 effective way if you know ID and don't have entity loaded is to create fake entity and delete it

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

But this won't work if you really have several records with the same id and you need to use name field as well to select right one.

Also your last example should be

var pg = dbContext.Program.First(p => p.Id == Id && p.Name == FName);
dbContext.Program.Remove(pg);
like image 196
vittore Avatar answered Sep 21 '22 12:09

vittore