Exemplo n.º 1
0
        public async Task <ActionResult <City> > Post(City city)
        {
            try
            {
                var existingCity = await repository.GetCity(city.CityName);

                if (existingCity != null)
                {
                    return(BadRequest($"City : {city.CityName} already exists"));
                }
                var location = linkGenerator.GetPathByAction("Get",
                                                             "Cities",
                                                             new { cityName = city.CityName });

                repository.Add(city);

                if (await repository.SaveChangesAsync())
                {
                    lastId = city.CityId;
                    return(Created(location, mapper.Map <CityDto>(city)));
                }
            }
            catch (Exception ex)
            {
                return(StatusCode(StatusCodes.Status500InternalServerError, ex.Message.ToString()));
            }
            return(BadRequest());
        }
        public async Task <ActionResult <AddressDto> > Post(string city, Address address)
        {
            try
            {
                var existingCity = await repository.GetCity(city);

                if (existingCity == null)
                {
                    return(BadRequest($"{city} does not exists"));
                }

                var existingAddress = existingCity.Addresses;
                if (existingAddress != null)
                {
                    foreach (var adr in existingAddress)
                    {
                        if (adr.AddressId == address.AddressId)
                        {
                            return(BadRequest($"Address : {address.StreetName} {address.AddressId} already exists"));
                        }
                    }
                }
                if (existingAddress == null)
                {
                    existingAddress = new List <Address>();
                }
                address.CityName = city;
                existingAddress.Add(address);

                if (await repository.SaveChangesAsync())
                {
                    var location = linkGenerator.GetPathByAction("Get",
                                                                 "Addresses",
                                                                 values: new { city = city, addressName = address.StreetName });

                    lastAddressId = address.AddressId;
                    lastCityName  = address.CityName;
                    return(Created(location, mapper.Map <AddressDto>(address)));
                }
            }
            catch (Exception ex)
            {
                return(StatusCode(StatusCodes.Status500InternalServerError, ex.Message.ToString()));
            }
            return(BadRequest());
        }