Ejemplo n.º 1
0
        public async Task <IActionResult> Create([Bind("Id,Title,ReleaseDate,Genre,Price")] Movie movie)
        {
            if (ModelState.IsValid)
            {
                _context.Add(movie);
                await _context.SaveChangesAsync();

                return(RedirectToAction(nameof(Index)));
            }
            return(View(movie));
        }
Ejemplo n.º 2
0
        static void AddAMovie()
        {
            using (var db = new MoviesDBContext(options))
            {
                // get first alphabetical name
                // (no network access yet!)
                var firstMovieQuery = db.Movie.Include(m => m.Genre).OrderBy(m => m.Name);

                Movie movie = firstMovieQuery.First();
                // that fetched only the one movie, not all of them

                var newMovie = new Movie {
                    Name = movie.Name + " 2", Genre = movie.Genre
                };

                // few different ways to add this. (aka track the entity)
                db.Add(newMovie); // this one guesses which DbSet based on the type.
                //db.Movie.Add(newMovie);

                // we can add this movie to the genre's navigation property "Movie" collection.
                //movie.Genre.Movie.Add(newMovie);

                // after doing any of those, the change to the database is recorded in the DbContext
                // but not yet applied to the DB.

                // SaveChanges applies all the tracked changes in one transaction
                db.SaveChanges();

                // now, those extra properties on the newMovie that we didn't set (like Id)
                // have been filled in by the dbcontext.

                // (you can continue working and savechanges multiple times on one dbcontext)
            }

            // objects you get out of the DbSets are "tracked" by the context.
            // any changes you make to them will be noticed and applied to the DB
            // on the next SaveChanges.

            // objects you create yourself are NOT tracked - track them with db.Add,
            // db.Update, or adding them to a tracked entity's navigation property.
        }