Update Operator in ASP.NET Web API and Entity Framework


Create a database with the name is LearnASPNETWebAPIWithRealApps. This database have a table: product table.

--
-- Table structure for table `product`
--

CREATE TABLE Product (
	Id int IDENTITY(1,1) NOT NULL PRIMARY KEY,
	Name varchar(50) NULL,
	Price money NULL,
	Quantity int NULL,
	Status bit NULL,
	CreationDate date NULL
)

--
-- Dumping data for table `product`
--

INSERT Product (Name, Price, Quantity, Status, CreationDate) VALUES ('Name 1', 12.3000, 3, true, '2017-10-20')
INSERT Product (Name, Price, Quantity, Status, CreationDate) VALUES ('Name 2', 25.1000, 8, false, '2017-11-12')
INSERT Product (Name, Price, Quantity, Status, CreationDate) VALUES ('Name 3', 23.9000, 2, true, '2017-12-26')
INSERT Product (Name, Price, Quantity, Status, CreationDate) VALUES ('Name 4', 89.2000, 11, false, '2017-09-17')

Structure of Product Table

Data of Product Table




Create entity class – ProductEntity.cs, to represent the above table

ProductEntity.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace LearnASPNETWebAPIWithRealApps.Models
{
    public class ProductEntity
    {
        public int Id
        {
            get;
            set;
        }

        public string Name
        {
            get;
            set;
        }

        public decimal Price
        {
            get;
            set;
        }

        public int Quantity
        {
            get;
            set;
        }

        public bool Status
        {
            get;
            set;
        }

        public string CreationDate
        {
            get;
            set;
        }

    }
}

Use the Entity Wizard to create an Entity Data Model From Database in Visual Studio.

Structure of Project




Create Web API Controller use Entity Framework get application/json data from the client and use Entity Framework update to database

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using LearnASPNETWebAPIWithRealApps.Models;
using Newtonsoft.Json;
using System.Net.Http.Headers;
using System.Data.Entity;

namespace LearnASPNETWebAPIWithRealApps.Controllers
{

    [RoutePrefix("api/product")]
    public class ProductRestController : ApiController
    {
        private LearnASPNETWebAPIWithRealAppsEntities db = new LearnASPNETWebAPIWithRealAppsEntities();

        [HttpPut]
        [Route("update")]
        public HttpResponseMessage update(ProductEntity productEntity)
        {
            try
            {
                var response = new HttpResponseMessage(HttpStatusCode.OK);
                var currentProduct = db.Products.SingleOrDefault(p => p.Id == productEntity.Id);
                currentProduct.Name = productEntity.Name;
                currentProduct.Price = productEntity.Price;
                currentProduct.Quantity = productEntity.Quantity;
                currentProduct.Status = productEntity.Status;
                currentProduct.CreationDate = Convert.ToDateTime(productEntity.CreationDate);
                db.SaveChanges();
                return response;
            }
            catch
            {
                return new HttpResponseMessage(HttpStatusCode.BadRequest);
            }
        }

    }
}

Create Console Application Project in Visual Studio

Create Models folder in Console Application. Create a entity class: ProductEntity.cs as below

Product.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace LearnASPNETWebAPIWithRealApps_Client.Models
{
    public class ProductEntity
    {
        public int Id
        {
            get;
            set;
        }

        public string Name
        {
            get;
            set;
        }

        public decimal Price
        {
            get;
            set;
        }

        public int Quantity
        {
            get;
            set;
        }

        public bool Status
        {
            get;
            set;
        }

        public string CreationDate
        {
            get;
            set;
        }

    }
}




DemoRestClientModel class contain methods call Web API. Add reference to System.Net.Http.Formatting

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Threading.Tasks;
using System.Net.Http;
using System.Net.Http.Headers;
using LearnASPNETWebAPIWithRealApps_Client.Models;

namespace LearnASPNETWebAPIWithRealApps_Client
{
    public class DemoRestClientModel
    {
        private string BASE_URL = "http://localhost:64967/api/product/";

        public Task<HttpResponseMessage> update(ProductEntity productEntity)
        {
            try
            {
                HttpClient client = new HttpClient();
                client.BaseAddress = new Uri(BASE_URL);
                client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));
                return client.PutAsJsonAsync("update", productEntity);
            }
            catch
            {
                return null;
            }
        }

    }
}
using LearnASPNETWebAPIWithRealApps_Client.Models;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;

namespace LearnASPNETWebAPIWithRealApps_Client
{
    class Program
    {
        static void Main(string[] args)
        {
            DemoRestClientModel demoRestClientModel = new DemoRestClientModel();

            var productEntity = new ProductEntity() {
                Id = 5,
                Name = "abc",
                Price = 888,
                Quantity = 333,
                Status = false,
                CreationDate = DateTime.Now.ToString("yyyy-MM-dd")
            };

            HttpResponseMessage httpResponseMessage = demoRestClientModel.update(productEntity).Result;

            HttpStatusCode httpStatusCode = httpResponseMessage.StatusCode;
            Console.WriteLine("Status Code: " + httpStatusCode);

            bool isSuccessStatusCode = httpResponseMessage.IsSuccessStatusCode;
            Console.WriteLine("IsSuccessStatusCode: " + isSuccessStatusCode);

            Console.ReadLine();
        }
    }
}




Status Code: OK
IsSuccessStatusCode: True