Hamoudy
Hamoudy

Reputation: 579

The object cannot be deleted because it was not found in the ObjectStateManager #2

I get the problem in the screenshot: problem

Here is the code at the beginning of the program:

    public MainWindow()
    {
        InitializeComponent();


        BlackoutDates();

        variables.date = Convert.ToDateTime(MainCalendar.DisplayDate);
        DateOutput.Content = MainCalendar.DisplayDate.DayOfWeek + ", " + MainCalendar.DisplayDate.ToShortDateString();



    }

    //initialises entities
    WpfApplication7.AllensCroftEntities1 allensCroftEntities1 = new WpfApplication7.AllensCroftEntities1();
    private Booking ObjectIndex;

Here is the code when the window is loaded

 private void Bookings_Loaded(object sender, RoutedEventArgs e)
    {


       WpfApplication7.AllensCroftEntities1 allensCroftEntities1 = new WpfApplication7.AllensCroftEntities1();
        // Load data into Rooms.
        var roomsViewSource = ((CollectionViewSource)(this.FindResource("roomsViewSource")));
        var roomsQuery = this.GetRoomsQuery(allensCroftEntities1);
        roomsViewSource.Source = roomsQuery.Execute(MergeOption.AppendOnly);

    }

Here is the code for the delete button which causes the error:

 private void btnDelete_Click(object sender, RoutedEventArgs e)
    {

        //prevents user trying to delete nothing/unselected row
        if (ObjectIndex == null)
        {
            MessageBox.Show("Cannot delete the blank entry");
        }
        else
        {

            //deletes object from dataset, saves it and outputs a message
            allensCroftEntities1.DeleteObject(ObjectIndex);

            allensCroftEntities1.SaveChanges();
            MessageBox.Show("Booking Deleted");
        }
    }

Here is the code for the object index:

   private void listrow_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {

        //outputs index of the selected room
        ObjectIndex = listrow.SelectedItem as Booking;
    }

EDIT,

i tried

 allensCroftEntities1.Attach(ObjectIndex);

attach

EDIT,

When i comment out the entities in the bookings loaded event, I get this error, this code used to work fine, but i dont know why all of these problems are occurring.

nullable

Upvotes: 1

Views: 4477

Answers (1)

MarcinJuraszek
MarcinJuraszek

Reputation: 125610

Try attaching entity to the context first:

allensCroftEntities1.Attach(ObjectIndex);
allensCroftEntities1.DeleteObject(ObjectIndex);

Or use context declared in class scope instead of local one within Bookings_Loaded event handler by deleting that line:

WpfApplication7.AllensCroftEntities1 allensCroftEntities1 = new WpfApplication7.AllensCroftEntities1();

Upvotes: 2

Related Questions