Glory Raj
Glory Raj

Reputation: 17701

Invalid operation exception was unhandled

I am trying to delete the record from an entity

got an error: Invalid operation exception The object cannot be deleted because it was not found in the ObjectStateManager.

and the code is like this...


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();

}

would any one pls help on this...

Modified code :


public partial class ProductDescriptionForm : Form {
    public TsgEntities tsgentity;
    public ProductDescriptionForm() {
        InitializeComponent();
        tsgentity = new TSGEntities();
    }

Upvotes: 1

Views: 1394

Answers (1)

Diadistis
Diadistis

Reputation: 12174

The problem is that you are trying to delete an object that is not tracked by the context.

The proper way to delete without fetching is to create an instance (only the id is actually needed), attach it to the context and then delete it :

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

Upvotes: 2

Related Questions