Jasper
Jasper

Reputation: 127

Delete Access record that has foreign key constraint

I'm making a WPF project based on an Access database. The database has two tables:

Problem is if I want to delete a movie, I get an error if there are still actors attached to the movie.

My code for deleting a movie:

public static void DeleteMovie(Movie mov)
{
        string commandString = string.Format("DELETE FROM tblMovies WHERE MovieID = {0}", mov.MovieID);

        OleDbConnection conn = new OleDbConnection(connectionString);
        OleDbCommand command = new OleDbCommand();
        OleDbDataAdapter adapter = new OleDbDataAdapter();
        conn.Open();

        command.Connection = conn;
        command.CommandText = commandString;
        adapter.DeleteCommand = command;
        adapter.DeleteCommand.ExecuteNonQuery();
        conn.Close();
}

As a temporarily solution I've added a messagebox that asks for confirmation if the actors are deleted from the movie. But if they aren't and you click yes, this happens:

Movie mov = (Movie)listBoxMovies.SelectedItem;
MovieRepository.DeleteMovie(mov);
MessageBox.Show("The movie: '" + mov.Title + " 'has been deleted.");

The error I get I want to delete a movie that has actors with the same MovieID:

An unhandled exception of type 'System.Data.OleDb.OleDbException' occurred in System.Data.dll Additional information: The record cannot be deleted or changed because table 'tblActors' includes related records.

How can I make it so that if I click the "delete movie" button, both the movie and the respective actors are deleted?

Upvotes: 4

Views: 754

Answers (1)

user5886152
user5886152

Reputation:

You can either write 2 queries - one to delete actors first, then the movie.

Or, you can go into Access and edit the relationship to "Cascade Delete Related Records".

To get there, go into Access, go to Database Tools and click Relationships. Right-click the relationship arrow from Movies to Actors, click "Edit Relationship", and you'll find the options there.

Upvotes: 3

Related Questions