简体   繁体   English

删除具有外键约束的访问记录

[英]Delete Access record that has foreign key constraint

I'm making a WPF project based on an Access database.我正在制作一个基于 Access 数据库的 WPF 项目。 The database has two tables:数据库有两个表:

  • Movies (MovieID: PK, Title, Director etc)电影(电影 ID:PK、标题、导演等)
  • Actors (ActorID: PK, MovieID: FK, Firstname, Lastname etc)演员(ActorID:PK,MovieID:FK,名字,姓氏等)

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:我得到的错误是我想删除演员具有相同 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. System.Data.dll 中发生类型为“System.Data.OleDb.OleDbException”的未处理异常 附加信息:无法删除或更改记录,因为表“tblActors”包含相关记录。

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.您可以编写 2 个查询 - 首先删除演员,然后删除电影。

Or, you can go into Access and edit the relationship to "Cascade Delete Related Records".或者,您可以进入 Access 并编辑与“级联删除相关记录”的关系。

To get there, go into Access, go to Database Tools and click Relationships.要到达那里,请进入 Access,转到数据库工具并单击关系。 Right-click the relationship arrow from Movies to Actors, click "Edit Relationship", and you'll find the options there.右键单击从电影到演员的关系箭头,单击“编辑关系”,您将在那里找到选项。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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