Entity Framework Delete Object Problem

ado.net c# entity-framework

Question

i am getting "The object cannot be deleted because it was not found in the ObjectStateManager". while Deleting object.

here is codes ;

//first i am filling listview control.
 private void Form1_Load(object sender, EventArgs e)
    {
        FirebirdEntity asa = new FirebirdEntity();

        ObjectQuery<NEW_TABLE> sorgu = asa.NEW_TABLE;

        foreach (var item in sorgu)
        {
            ListViewItem list = new ListViewItem();
            list.Text = item.AD;
            list.SubItems.Add(item.SOYAD);
            list.Tag = item;
            listView1.Items.Add(list);

        }
//than getting New_table entity from listview's tag property.
 private void button3_Click(object sender, EventArgs e)
    {

            using (FirebirdEntity arama = new FirebirdEntity())
            {

               NEW_TABLE del = (NEW_TABLE)listView1.SelectedItems[0].Tag;
               arama.DeleteObject(del);
               arama.SaveChanges();


            }}
1
14
8/1/2009 5:21:54 PM

Accepted Answer

You need to attach the object to the ObjectContext. Try:

NEW_TABLE del = (NEW_TABLE)listView1.SelectedItems[0].Tag;
arama.Attach(del);
arama.DeleteObject(del);
arama.SaveChanges();

Attached objects are tracked by the ObjectContext. This is needed for performing deletes and updates. You can read more about attaching objects on MSDN.

Edit to clarify attach/detach:

private void Form1_Load(object sender, EventArgs e) {
    FirebirdEntity asa = new FirebirdEntity();

    ObjectQuery<NEW_TABLE> sorgu = asa.NEW_TABLE;
    foreach (var item in sorgu) {
        asa.Detach(item);
        // add to listView1
    }
}

Also, you should wrap your use of ObjectContexts in using blocks.

28
8/1/2009 11:53:01 PM

Popular Answer

In your method "Form1_Load" you create a FIRST instance of your "FirebirdEntity" context an fill the ListViewItem with entities selected from this context

In your method "button3_Click" you create a NEW, SECOND instance of your "FirebirdEntity" context. Then you try to delete an entity in this SECOND context, which was selected in the FIRST context.

Use the same instance of your context in both of your methods and everything will work fine.

(Alternatively you can select the entity you want to delete a from your SECOND context and then delete this entity instead of the origin one)



Related Questions





Related

Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow
Licensed under: CC-BY-SA with attribution
Not affiliated with Stack Overflow