我有这个SQL数据库设置:
我现在有一部电影有2种类型和2个演员。我想要删除这部电影,而这只是:
movie = (Movie)listBoxMovieExistingMovies.SelectedItem;
db.Movies.Remove(movie);
db.SaveChanges();
LoadMovieExistingMovies();
我知道我必须首先删除关系,但我无法弄清楚如何做到这一点。
编辑:
(我如何创建MovieActor和MovieGenres)
CREATE TABLE MovieGenre
(
MovieID int NOT NULL REFERENCES Movie(MovieID),
GenreID int NOT NULL REFERENCES Genre(GenreID),
PRIMARY KEY(MovieID,GenreID)
)
答案 0 :(得分:0)
您是否需要先从上下文中选择电影?
movie = db.Movies.FirstOrDefault(m => m.MovieId == ((Movie)listBoxMovieExistingMovies.SelectedItem).MovieId);
db.Movies.Remove(movie);
db.SaveChanges();
LoadMovieExistingMovies();
答案 1 :(得分:0)
尝试使用db
上的级联删除CREATE TABLE [dbo].[MovieActor](
[MovieId] [int] NOT NULL,
[ActorId] [int] NOT NULL
) ON [PRIMARY]
GO
ALTER TABLE [dbo].[MovieActor] WITH CHECK ADD CONSTRAINT [FK_MovieActor_Actor] FOREIGN KEY([ActorId])
REFERENCES [dbo].[Actor] ([Id]) ON DELETE CASCADE
GO
ALTER TABLE [dbo].[MovieActor] CHECK CONSTRAINT [FK_MovieActor_Actor]
GO
ALTER TABLE [dbo].[MovieActor] WITH CHECK ADD CONSTRAINT [FK_MovieActor_Movie] FOREIGN KEY([MovieId])
REFERENCES [dbo].[Movie] ([Id]) ON DELETE CASCADE
GO
ALTER TABLE [dbo].[MovieActor] CHECK CONSTRAINT [FK_MovieActor_Movie]
GO
如果您采用此解决方案,请花点时间阅读有关级联的信息。
答案 2 :(得分:0)
我发现了两种方法
1:
movie = (Movie)listBoxMovieExistingMovies.SelectedItem;
var queryMovie = db.Movies.Include("Genres").Include("Actors").First(m => m.MovieID==movie.MovieID);
db.Movies.Remove(queryMovie);
2:
movie = (Movie)listBoxMovieExistingMovies.SelectedItem;
movie.Actors.Clear();
movie.Genres.Clear();
db.Movies.Remove(movie);
db.SaveChanges();