未处理的操作异常无效

时间:2011-08-19 13:27:13

标签: c# linq entity-framework linq-to-entities

我正在尝试从实体中删除记录

出错:无效的操作异常 无法删除该对象,因为在ObjectStateManager中找不到该对象。

并且代码是这样的......


private void btnProdDelete_Click(object sender, EventArgs e){
    Image image = pictureBox1.Image;
    byte[] bit = null;

bit = imageToByteArray(image);

//var c = new category {
//  category_Name = tbCategoryName.Text,
//  category_Description = tbCategoryDescription.Text
//};

product pd = new product();
pd.product_Id = productid;
pd.product_Name = tbProductName.Text;
decimal price = Convert.ToDecimal(tbProductPrice.Text);
pd.product_Price = price;
pd.product_Description = tbProductdescription.Text;
pd.product_Image = bit;

tsgentity.DeleteObject(pd);
this.Close();

}

任何人都会帮忙...

修改后的代码

bit = imageToByteArray(image);

//var c = new category {
//  category_Name = tbCategoryName.Text,
//  category_Description = tbCategoryDescription.Text
//};

product pd = new product();
pd.product_Id = productid;
pd.product_Name = tbProductName.Text;
decimal price = Convert.ToDecimal(tbProductPrice.Text);
pd.product_Price = price;
pd.product_Description = tbProductdescription.Text;
pd.product_Image = bit;

tsgentity.DeleteObject(pd);
this.Close();

1 个答案:

答案 0 :(得分:2)

问题是您正在尝试删除未被上下文跟踪的对象。

删除而不提取的正确方法是创建一个实例(实际只需要id),将其附加到上下文然后删除它:

var pd = 
    new product() 
    {
        product_Id = productid,
        EntityKey = new EntityKey("product.id", "id", productid)
    };
tsgentity.Attach(pd);
tsgentity.DeleteObject(pd);