コード例 #1
0
        public async Task <IActionResult> Edit(DestinationViewModel model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    var city = await _countryRepository.GetCityAsync(model.CityId);

                    var country = await _countryRepository.GetByIdAsync(model.CountryId);

                    var user = await _userHelper.GetUserByIdAsync(model.UserId);

                    Destination destination = new Destination()
                    {
                        Id      = model.Id,
                        IATA    = model.IATA,
                        Airport = model.Airport,
                        City    = city,
                        Country = country,
                        User    = user
                    };

                    try
                    {
                        await _repository.UpDateAsync(destination); // O método Update já grava as alterações

                        return(RedirectToAction(nameof(Index)));
                    }
                    catch (Exception ex)
                    {
                        if (ex.InnerException.Message.Contains("duplicate"))
                        {
                            GetCombos(model);
                            model.CountryId = country.Id;
                            model.CityId    = city.Id;
                            ModelState.AddModelError(string.Empty, "Already exists a destination with that IATA");
                            return(View(model));
                        }

                        else
                        {
                            model.CountryId = country.Id;
                            model.CityId    = city.Id;
                            GetCombos(model);
                            ModelState.AddModelError(string.Empty, ex.InnerException.Message);
                            return(View(model));
                        }
                    }
                }

                catch (DbUpdateConcurrencyException)
                {
                    if (!await _repository.ExistsAsync(model.Id))
                    {
                        return(NotFound());
                    }
                    else
                    {
                        return(View(model));
                    }
                }
            }
            GetCombos(model);
            return(View(model));
        }