This is all refactorable, so if there’s a better way to approach the situation overall, let me know. This got wordy really quick, sorry.
I’m creating a movie database, and I’ve got 3 tables, Movies, Genres and MovieToGenre. I’ve created the Genre table, and to populate the MtG table, I’m trying to associate a genre_id with a movie_id, which is a one-to-many relationship, I think, so it’ll have something like the following in it
movie_id | genre_id
1 56
1 786
2 232
2 656
But my issue is that in order to fill that table, I need the movie_id from the Movie model. I assumed that once I’ve added the Movie to the Movies table, that the model would retroactively update its movie_id property, but that doesn’t seem to be the case, as the MovieToGenre table gets populated with movie_id‘s equalling 0, the default value. The Movies table is using the proper movie_id so it’s a matter of telling my FillMovieToGenre method which movie has what movie_id.
The general process I’m using is the following loop:
-
Create
Movieinstance, not setting themovie_id, since MVC
chooses one itselfa.
movie = new Movie(data1, data2) -
Add
Movieinstance to tablea.
db.Movies.Add(movie) -
Use the last
Movieinstance’smovie_idin a
FillMovieToGenreTable()method.a.
FillMtGTable(movie)But at this point, the movie does not contain the non-defaultmovie_idand so theMtGtable is filled withmovie_id = 0, where it should bemovie_id = 1231etc. -
GOTO 1.
tl;dr Possible to get a primary key for a recently added model? Seems like making a new query would be a bad idea, since I’m looping over all the movies I need to add, and that new query would slow the process down, I’d think.
edited in the relevant parts of the Movie class
public class Movie
{
[Key]
public int movie_ID { get; set; }
[DisplayName("Title")]
public string title { get; set; }
}
public class Genre
{
[DisplayName("Genre ID")]
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.None)]
public int genre_ID { get; set; }
[DisplayName("Genre")]
public string genre_string { get; set; }
}
public class MovieToGenre
{
[Key]
public int movie_to_genre_ID { get; set; }
public virtual int movie_ID { get; set; }
public virtual int genre_ID { get; set; }
}
In EF after you save changes in other words after you run
EF should automatically give you the populated ID