Fred
Fred

Reputation: 5808

How to return the ID of each record after insert using EF

I have a data class with nested Lists. A simplified example (not real code):

public class Movie
{
    public Int32 TVIndex;
    public string MovieName;
    public string MovieRating;
    public string MovieRuntime;
    public List<Actor> MovieActors;
    public List<MovieArt> MovieImages;
}



public class Actor
{
    public string ActorName;
    public string ActorRole;
}

public class MovieArt
{
    public string ImagePath;
}


List<Movie> myMovies = new List<Movie>(); 

This may contain many movies and each movie may contain many Actors and many MovieArt.

I pass this list to a web service that inserts the records into tables using DataEntityModel.

Something Like..

    public void InsertMovies(List<Movie> request)
    {

            using (TransactionScope scope = new TransactionScope())
            {
                using (MyMovieStorageEntities DbContext = new MyMovieStorageEntities())
                {
                    foreach (Movie m in request)
                    {
                        Movies movie = new Movies();

                        movie.MovieName = m.MovieName;
                        movie.MovieRating = m.MovieRating;
                        movie.MovieRuntime = m.MovieRuntime;

                        DbContext.DBMovies.Add(movie);

                        foreach (Actor a in m.MovieActors)
                        {
                            Actors actor = new Actors();
                            actor.ActorName = a.ActorName;
                            actor.ActorRole = a.ActorRole;
                            DbContext.DBActors.Add(actor);

                        }

                        for (MovieArt i in m.MovieImages)
                        {
                            MovieArt artwork = new MovieArt();
                            artwork.FileName = i.FileName;
                            DbContext.DBMovieArt.Add(artwork);
                        }
                    }

                    DbContext.SaveChanges();
                }

           }
    }

In the Movie table is an Identity column and I need to return the identity for each inserted record for use in the client app.

I am new to DataEntity and not really sure where to start. All the searching I have done hasn't really helped. Any pointers?

Upvotes: 0

Views: 565

Answers (2)

ElectricRouge
ElectricRouge

Reputation: 1279

EF automatically returns the ID. movie.ID gives you the last inserted ID you can use it or return it from your method to use somewhere else.

Upvotes: 0

Jon Barker
Jon Barker

Reputation: 1828

Don't lose the references to your entity framework objects (e.g. add them to a list), and after SaveChanges(), the object property containing the primary key will be automatically updated with the ID.

See here for more info How can I get Id of inserted entity in Entity framework?

Upvotes: 2

Related Questions