コード例 #1
0
        public async Task <ActionResult> Save(Customer customer)
        {
            if (!ModelState.IsValid)
            {
                CustomerFormViewModel model = new CustomerFormViewModel
                {
                    Customer    = customer,
                    Memberships = await _context.Memberships.ToListAsync()
                };
                return(View("Form", model));
            }

            if (customer.Id == null)
            {
                _context.Customers.Add(customer);
            }
            else
            {
                _context.Entry(customer).State = EntityState.Modified;
            }

            await _context.SaveChangesAsync();

            return(RedirectToAction("Index"));
        }
コード例 #2
0
        public async Task <IHttpActionResult> Put([FromBody] Movie movie)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            //Update
            _context.Entry(movie).State = EntityState.Modified;
            await _context.SaveChangesAsync();

            return(Ok());
        }
コード例 #3
0
        public async Task <ActionResult> Save(MovieFormViewModel model)
        {
            IEnumerable <int> genreIds = model.Genres.Where(g => g.IsChecked).Select(g => g.Id);

            if (!genreIds.Any())
            {
                ModelState.AddModelError("MinOneGenre", "Movie should have at least one Genre");
            }

            if (!ModelState.IsValid)
            {
                //model.Genres = _context.Genres.Select(g => new GenreVm { Id = g.Id, Name = g.Name }).ToList();
                //Parallel.ForEach(model.Genres.Where(g => genreIds.Contains(g.Id)), g => g.IsChecked = true);

                model.Genres.ForEach(async g => g.Name = (await _context.Genres.FindAsync(g.Id)).Name);
                return(View("Form", model));
            }

            List <Genre> genresOnDb = await _context.Genres.Where(g => genreIds.Contains(g.Id)).ToListAsync();

            model.Movie.Genres = new List <Genre>();


            if (model.Movie.Id == null)
            {
                model.Movie.Genres.AddRange(genresOnDb);
                _context.Movies.Add(model.Movie);
            }
            else
            {
                _context.Entry(model.Movie).State = EntityState.Modified;

                Movie movieOnDb = await _context.Movies.Include(m => m.Genres).SingleAsync(m => m.Id == model.Movie.Id);

                movieOnDb.Genres.RemoveAll(g => true);
                movieOnDb.Genres.AddRange(genresOnDb);
            }


            _context.SaveChanges();
            return(RedirectToAction("Index"));
        }