Exemplo n.º 1
0
        public async Task <IActionResult> RemovePeople([FromForm] RemovePeopleFromCity remove)
        {
            if (remove.CityId == Guid.Empty)
            {
                ModelState.AddModelError(string.Empty, "The Id could not be fetched.");

                return(BadRequest(ModelState));
            }

            var result = await _service.RemovePeople(remove);

            if (result.Message == ActionMessages.Updated)
            {
                return(RedirectToAction(nameof(Details), "City", new { id = result.City.Id, updated = true }));
            }
            else if (result.Message == ActionMessages.NotFound)
            {
                ModelState.AddModelError(string.Empty, "The requested city could not be found.");

                return(NotFound(ModelState));
            }
            else
            {
                ModelState.AddModelError(string.Empty, $"Error Type: {result.Message.ToString()}");

                return(BadRequest(ModelState));
            }
        }
Exemplo n.º 2
0
        public async Task <CityWithMessage> RemovePeople(RemovePeopleFromCity remove)
        {
            try
            {
                if (remove.CityId == Guid.Empty)
                {
                    throw new Exception();
                }

                if (remove.PeopleId == null || remove.PeopleId.Count == 0)
                {
                    return(new CityWithMessage {
                        Message = ActionMessages.Empty
                    });
                }

                var city = await _db.Cities
                           .Include(x => x.People)  // IMPORTANT: Forget this and it won't remove any people.
                           .Include(x => x.Country) // And this for the View.
                           .SingleOrDefaultAsync(x => x.Id == remove.CityId);

                if (city == null)
                {
                    return(new CityWithMessage {
                        Message = ActionMessages.NotFound
                    });
                }

                foreach (var personId in remove.PeopleId)
                {
                    var person = await _db.People.SingleOrDefaultAsync(x => x.Id == personId) ?? throw new Exception();

                    if (city.People.Contains(person))
                    {
                        city.People.Remove(person);
                    }
                }

                await _db.SaveChangesAsync();

                return(new CityWithMessage {
                    City = city, Message = ActionMessages.Updated
                });
            }
            catch (Exception)
            {
                return(new CityWithMessage {
                    Message = ActionMessages.Failed
                });
            }
        }