使用linq删除gridview中的行

时间:2015-04-28 19:23:12

标签: c# linq entity-framework

我编写了这段代码来删除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";
    }
}

1 个答案:

答案 0 :(得分:0)

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