简体   繁体   中英

How to get a primary key from a model without querying the DB once I've added the model?

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:

  1. Create Movie instance, not setting the movie_id , since MVC chooses one itself

    a. movie = new Movie(data1, data2)

  2. Add Movie instance to table

    a. db.Movies.Add(movie)

  3. Use the last Movie instance's movie_id in a FillMovieToGenreTable() method.

    a. FillMtGTable(movie) But at this point, the movie does not contain the non-default movie_id and so the MtG table is filled with movie_id = 0 , where it should be movie_id = 1231 etc.

  4. 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

db.Movies.Add(movie)
db.SaveChanges();

EF should automatically give you the populated ID

int movie_id=movie.movie_id;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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