Exemple #1
0
        public IHttpActionResult Put(Product product)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest("The data you entered is not valid"));
            }

            using (var ctx = new EmployeeDBEntities_Product())
            {
                var existingProduct = ctx.Products.FirstOrDefault(p => p.ProductId == product.ProductId);
                if (existingProduct != null)
                {
                    existingProduct.Name        = product.Name;
                    existingProduct.Description = product.Description;
                    existingProduct.Price       = product.Price;

                    ctx.SaveChanges();
                }
                else
                {
                    return(NotFound());
                }
            }

            return(Ok());
        }
Exemple #2
0
        public IHttpActionResult Delete(int id)
        {
            if (id < 0)
            {
                return(BadRequest("Not a valid Product Id"));
            }

            using (var ctx = new EmployeeDBEntities_Product())
            {
                var product = ctx.Products.FirstOrDefault(p => p.ProductId == id);

                ctx.Entry(product).State = System.Data.Entity.EntityState.Deleted;
                ctx.SaveChanges();
            }

            return(Ok());
        }
Exemple #3
0
        public IHttpActionResult PostNewProduct(Product product)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest("Not a valid model"));
            }

            using (var ctx = new EmployeeDBEntities_Product())
            {
                ctx.Products.Add(new Product()
                {
                    Name        = product.Name,
                    Description = product.Description,
                    Price       = product.Price
                });

                try
                {
                    ctx.SaveChanges();
                }
                catch (DbEntityValidationException e)
                {
                    foreach (var eve in e.EntityValidationErrors)
                    {
                        Console.WriteLine("Entity of type \"{0}\" in state \"{1}\" has the following validation errors:",
                                          eve.Entry.Entity.GetType().Name, eve.Entry.State);
                        foreach (var ve in eve.ValidationErrors)
                        {
                            Console.WriteLine("- Property: \"{0}\", Value: \"{1}\", Error: \"{2}\"",
                                              ve.PropertyName,
                                              eve.Entry.CurrentValues.GetValue <object>(ve.PropertyName),
                                              ve.ErrorMessage);
                        }
                    }
                    throw;
                }
            }

            return(Ok());
        }