Entity Framework dbset most efficient way of deleting

dbset entity-framework linq

Question

I have the following and am searching for a quicker approach to delete them than cycling over them one by one (note that I'm using Dbset):

     var wcd = dbContext.ProgramDetails.Where(p => p.Id == Id);

     foreach (var wc in wcd.ToList())
     {
        dbContext.ProgramDetails.Remove(wc);
     }

     dbContext.SaveChanges();

Say further that if we just have one record, it is as follows:

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

What's the easiest technique to get rid of this particular record?

attempted this but received a failure:

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

Then, as I've shown above, I fell back on using a foreach to delete only one entry, which is not the most effective method.

1
11
10/11/2012 2:00:00 AM

Accepted Answer

ADVANCED FOR EF7:

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

Check the updated documents for msdn and examples on ADVANCED MAY 2015. Example of EF6 deletion code for an entity

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

If you know your ID and don't already have an entity loaded, the best strategy is to build a false entity and remove it.

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

However, if you really have many records with the same ID and you need to utilize one of them, this won't work.name field as well to make the proper choice.

Your final illustration should be

var pg = dbContext.Program.First(p => p.Id == Id && p.Name == FName);
dbContext.Program.Remove(pg);
11
7/19/2017 12:48:11 AM


Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow