删除多个项目 C# EF

Delete multiples items C# EF

我正在使用 Entity Framework。

try
{
    List<DataGridViewRow> selectedRows = (from row in dtg.Rows.Cast<DataGridViewRow>()
                                          where Convert.ToBoolean(row.Cells["Borrar"].Value) == true
                                          select row).ToList();
    if (MessageBox.Show(string.Format("¿Deseas borrar {0} registros?", selectedRows.Count), "Confirmacion", MessageBoxButtons.YesNo) == DialogResult.Yes)
    {
        foreach (DataGridViewRow row in selectedRows)
        {
            using (var context = new SistemaVentasEntities())
            {
                REGISTROS registro= context.AUX_REGISTROS .Where(m => m.ID== m.ID).FirstOrDefault();
                context.REGISTROS.Remove(registro);
                context.SaveChanges();
            }
            this.CargarGrid();
        }
    }
}
catch (Exception ex)
{
    MessageBox.Show(ex.Message + ex.StackTrace);
}

到这里,一切正确,排除了我select的记录数。但只是连续的,我只想删除项目 selected,如果我有一个 ID { 1,2,3,4 } 的列表并且我想删除 1 和 3,它不起作用,该代码删除了例如 1 和 2。

我在 DataGridView 中使用复选框,单击按钮。

我猜。在实际删除实体之前,首先尝试找到然后将它们放入单独的集合中,然后在 separate 循环中将它们从数据库中删除,然后在上下文中调用保存更改。我敢打赌,您是在某种程度上修改循环所依据的集合。这导致您出现选择性删除问题。

我认为您的问题出在这一点上:

.Where(m => m.ID== m.ID)

您正在将过滤器中的 ID 与过滤器中的 ID 进行比较(永远为真)。我想你想要这样的东西:

.Where(m => m.ID == row.ID)

... 除了从您的行中检索您的 ID 的代码可能就是这样。 :)

EntityFramework.Extended has a really nice extension method for this kind of jobs. You can find more details here.

来自文档页面的示例:

//delete all users where FirstName matches
context.Users
    .Where(u => u.FirstName == "firstname")
    .Delete();