实体框架数据库集最有效的删除方式



我有以下内容,正在寻找一种更有效的方法来删除与循环遍历记录然后一次删除每个记录(使用 Dbset 注意):

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

还要说我们有 1 条记录,如下所示:

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

删除此记录的最佳方法是什么?

尝试以下方法,但给出错误:

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

然后,我求助于仅删除一条记录的foreach,如我上面所示,这对于仅删除一条记录并不是最有效的。

EF7 的更新

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

2015 年 5 月更新:检查 msdn 上的更新文档和示例。使用 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); 
        } 
 } 

如果您知道ID并且没有加载实体,最有效的方法是创建假实体并将其删除

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

但是,如果您确实有几条具有相同 id 的记录,并且您还需要使用name字段来选择正确的记录,这将不起作用。

你的最后一个例子应该是

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

最新更新