public async Task <IHttpActionResult> Add(BuildingCreateModel building)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState));
            }

            Response result = await _buildingsService.Add(building);

            if (result.Ok)
            {
                return(StatusCode(HttpStatusCode.Created));
            }
            else
            {
                return(BadRequest(result.Message));
            }
        }
示例#2
0
        public async Task <Response> Add(BuildingCreateModel building)
        {
            if (building.Id != 0)
            {
                return(new Response {
                    Message = "Не корректный Id"
                });
            }

            building.AddressHashCode = building.Address.GetHashCode();

            List <BuildingModel> overlaps;

            if (building.WaterMeterId == 0)
            {
                building.WaterMeterId = null;
                overlaps = await _dbContext.Buildings.Where(b => b.AddressHashCode == building.AddressHashCode).ToListAsync();
            }
            else
            {
                overlaps = await _dbContext.Buildings.Where(b => b.AddressHashCode == building.AddressHashCode || b.WaterMeterId == building.WaterMeterId).ToListAsync();
            }

            foreach (var b in overlaps)
            {
                if (b.AddressHashCode == building.AddressHashCode)
                {
                    return new Response {
                               Message = "Такой адрес уже используется."
                    }
                }
                ;

                if (b.WaterMeterId == building.WaterMeterId)
                {
                    return new Response {
                               Message = $"Счетчик с таким s/n уже установлен по адресу {b.Address.ToString()}"
                    }
                }
                ;
            }

            BuildingModel convertBuilding = Mapper.Map <BuildingCreateModel, BuildingModel>(building);

            try
            {
                _dbContext.Buildings.Add(convertBuilding);

                await _dbContext.SaveChangesAsync();

                return(new Response {
                    Ok = true
                });
            }
            catch
            {
                return(new Response {
                    Message = "Произошла ошибка при добавлении. Пожалуйсте повторите попытку."
                });
            }
        }