C
C#•11mo ago
Denge

.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?
No description
No description
No description
No description
8 Replies
Jimmacle
Jimmacle•11mo ago
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
Denge
DengeOP•11mo ago
Forgot to include, here you go:
No description
Jimmacle
Jimmacle•11mo ago
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
Denge
DengeOP•11mo ago
Could you give an example of the above?
No description
No description
Jimmacle
Jimmacle•11mo ago
if you put those in intermediate collections you can access them by index then do new MovieGenre { Movie = Movies[0], Genre = Genres[0] } etc
Denge
DengeOP•11mo ago
It worked, thanks a lot 🙂
Jimmacle
Jimmacle•11mo ago
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
Denge
DengeOP•11mo ago
The id's didn't get reset to 0, that's why 🙂
No description
Want results from more Discord servers?
Add your server