Exemple #1
0
        public async Task <ActionResult <CategoriesModel> > Post(CategoriesModel model)
        {
            try
            {
                //Make sure to return an error if an existing Category Name is entered
                if (await _repository.GetCategoryByCategoryNameEn(model.CategoryNameEn) != null)
                {
                    return(StatusCode(StatusCodes.Status409Conflict, "The category already exists"));
                }

                //Return error if the name is null
                if (model.CategoryNameEn == null)
                {
                    return(BadRequest("Category Name cannot be empty"));
                }

                //Make sure to return error if an existing id is entered
                if (await _repository.GetCategoryById(model.Id) != null)
                {
                    return(StatusCode(StatusCodes.Status409Conflict, "The category already exists"));
                }

                if (ModelState.IsValid)
                {
                    var cat = _mapper.Map <Categories>(model);

                    _repository.AddCategory(cat);

                    if (await _repository.SaveChangesAsync())
                    {
                        var newModel = _mapper.Map <CategoriesModel>(cat);

                        return(CreatedAtRoute("", new { cat = newModel.CategoryNameEn }, newModel));
                    }
                }
            }
            catch (Exception ex)
            {
                return(StatusCode(StatusCodes.Status500InternalServerError, ex));
            }
            return(BadRequest(ModelState));
        }