简体   繁体   中英

Delete Access record that has foreign key constraint

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

  • Movies (MovieID: PK, Title, Director etc)
  • Actors (ActorID: PK, MovieID: FK, Firstname, Lastname etc)

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM