I assume this has a very simple answer. I am brand new to entity framework and I am creating a test application consisting of Contacts
and Groups
as objects/entities.
Here is my code to delete a group:
private void button_DeleteGroup_Click(object sender, EventArgs e)
{
var _selectedGroup = dataGridView_Groups.SelectedRows[0].DataBoundItem as Group;
try
{
cgContext.Groups.Remove(_selectedGroup);
cgContext.SaveChanges();
PopulateGroupGrid();
MessageBox.Show("Successfully deleted group from database!");
}
catch(Exception ex) { MessageBox.Show("Failed to delete group from database.\r\n\r\n" + ex); }
}
If I delete a group that a contact belongs to, to test referential integrity, an exception is thrown (as it should):
"The DELETE statement conflicted with the REFERENCE constraint "FK_dbo.Contacts_dbo.Groups_Group_Id". The conflict occurred in database "ContactGroups", table "dbo.Contacts", column 'Group_Id'. The statement has been terminated."
I then catch this exception and display a message to the user. If I then go to add a new group or contact or do anything, the transaction fails with the same exception as before:
"The DELETE statement conflicted with the REFERENCE constraint "FK_dbo.Contacts_dbo.Groups_Group_Id". The conflict occurred in database "ContactGroups", table "dbo.Contacts", column 'Group_Id'. The statement has been terminated."
So, obviously i'm not clearing / ending a transaction or something when the initial exception occurs. What am I doing wrong or missing?