11

我有以下内容,并正在寻找一种更有效的方式来删除与循环遍历记录,然后一次删除每个记录(注意使用 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 只删除一条记录,如上所示,这对于仅 1 条记录并不是最有效的。

4

1 回答 1

13

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)

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);
于 2012-10-11T02:04:40.970 回答