.NET Many to Many Relationship seeding error
Hey, I'm currently trying out my first little test project in .NET.
I have made some tables and I'm currently trying to seed my database, but I get the following error trying to run my program:
SqlException: The MERGE statement conflicted with the FOREIGN KEY constraint "FK_MovieGenres_Genres_GenreId". The conflict occurred in database "MovieApp", table "dbo.Genres", column 'GenreId'.
I have added some screenshots with the code.
Anyone knows how to solve?
8 Replies
your join entity isn't set up correctly, you can't just use the genre ID as a key because that limits you to one row per genre
wait, i was reading the wrong one
where is your MovieGenre class?
also as an aside, if you are doing a simple many-many with no extra data related to the relationship you don't need an explicit join entity/table
Forgot to include, here you go:
and where's the code where you seed the movies and genres?
IMO setting relationships using IDs is super error prone, use the actual objects instead since you have them
Could you give an example of the above?
if you put those in intermediate collections you can access them by index
then do
new MovieGenre { Movie = Movies[0], Genre = Genres[0] }
etcIt worked, thanks a lot 🙂
yeah the database was probably assigning IDs that weren't what you assumed
or the change tracker was just getting confused because you were trying to do it all at once
The id's didn't get reset to 0, that's why 🙂