Reputation: 95
I have a "DogDBContext" populated by Dog items, and my datagrid's ItemsSource is set to a List created by calling DogDBContext's ToList(). I have two buttons accompanying the datagrid: Add and Remove. Adding should let me add a random Dog to both the database and update the change accordingly in the datagrid; pressing Remove would remove the selected Dog from both the database and the datagrid. The Remove button's click handler looks like this:
private void removeDogButton_Click(object sender, RoutedEventArgs e)
{
var dog = dogDataGrid.SelectedItem;
dcList.Remove((Dog)dog1);
dc.Dogs.Remove((Dog)dog);
dogDataGrid.Items.Refresh();
}
This removes the selected Dog from the datagrid but not from the database. My first thought was to use dc.Dogs.Remove((Dog)dog) (where 'dc' is DogDBContext) but this threw an exception saying "The operation cannot be completed because the DBContext has been disposed". What does that mean and how do I appropriately remove the item from the database?
Upvotes: 1
Views: 250
Reputation: 141
For your exception you need to look where you are doing:
DogDBContext dc = new DogDBContext();
You need to instance dc at the declaration or in the constructor.
Then dc.Dogs.Remove((Dog)dog);
will be good and you need to call dc.SaveChanges()
for saving changes.
Ludo
Upvotes: 2