SimpleMerican
SimpleMerican

Reputation: 23

How to delete a row from a local sql server database in C#

I am currently creating an airline registration system project in C# for one of my classes. I am having trouble with deleting a row from one of my tables. It will allow me to add to the database using a textbox but will not allow me to remove a row using a textbox.

Here is my code:

    private void Button1_Click(object sender, EventArgs e)
    {
        AirlineEntities db = new AirlineEntities();
        TICKETING cancel = new TICKETING
        {
            TICK_ID = Convert.ToInt32(ticktxt.Text),
            CUSTOMER_ID = Convert.ToInt32(customertxt.Text),
            DATE = datetxt.Text,
            FLIGHT_ID = Convert.ToInt32(flighttxt.Text),
            SEAT_NUMBER = Convert.ToInt32(seattxt.Text)
        };

        db.TICKETINGs.Remove(cancel);
        db.SaveChanges();
        MessageBox.Show("Ticket Cancelled");
    }
}

The error code I get is as follows:

the object cannot be deleted because it was not found in the objectstatemanager

Any help would be greatly appreciated.

Upvotes: 1

Views: 280

Answers (1)

William Xifaras
William Xifaras

Reputation: 5312

Deleting entities via the DbContext depends on whether the context is currently tracking the entity being deleted or not.

In your case, you have to set the EntityState.

db.Entry(cancel).State = EntityState.Deleted;
db.SaveChanges();

Another approach is to have the context obtain the entity so the context begins tracking it immediately.

var ticketId = Convert.ToInt32(ticktxt.Text);
db.Remove(db.TICKETING.Single(t => t.TICK_ID == ticketId));
db.SaveChanges();

OR

var ticketId = Convert.ToInt32(ticktxt.Text);
var cancel = db.TICKETING.FirstOrDefault(t => t.TICK_ID == ticketId);  
db.Remove(cancel);  
db.SaveChanges();   

Upvotes: 3

Related Questions