我编写了这段代码以从Gridview删除行,但是它不起作用。

class.cs中的代码:

public bool bDeleteItem(int nItemID)
{
    bool flag = false;
    try
    {
        Training_sNairoukhEntities1 sNairoukhEntities1 = new Training_sNairoukhEntities1();
        IMS_Items oIMS_Items = sNairoukhEntities1.IMS_Items.Where(Entity => Entity.ItemID == nItemID).Single();
        sNairoukhEntities1.IMS_Items.Remove(oIMS_Items);
        int nResult = sNairoukhEntities1.SaveChanges();
        if (nResult > 0)
        {
            flag = true;
        }
    }
    catch (Exception ex)
    {
    }
    return flag;
}


Aspx.cs中的代码:

int nId = Convert.ToInt32(gvManageItem.DataKeys[Convert.ToInt32(e.CommandArgument)]["ItemID"].ToString());
if (e.CommandName == "cmDelete")
{
    ManageItem oManageItem = new ManageItem();
    if (oManageItem.bDeleteItem(nId))
    {
        lblValidation.Text = "Delete is successfully";
    }
    else
    {
        lblValidation.Text = "isnt delete";
    }
}

最佳答案

Remove方法:“将给定实体标记为Deleted,以便在调用SaveChanges时将其从数据库中删除。请注意,在调用此方法之前,该实体必须以某种其他状态存在于上下文中。”
下面的命令将起作用:
sNairoukhEntities1.Entry(oIMS_Items).State = System.Data.Entity.EntityState.Deleted;
sNairoukhEntities1.SaveChanges();

10-06 13:01