Web API2 CRUD operations using Entity Framework and MVC


In this blog, we will perform Web API CRUD operations using Entity Framework and ASP.Net MVC.

What is ASP.Net Web API?

Web API is the Microsoft open source technology for developing REST services based on HTTP protocol. ASP.Net Web API is a framework for building, consuming HTTP based service. The advantage of Web API is that it can be consumed by a wide range of clients like a web browser and mobile applications.

What is Entity Framework?

Entity Framework is an object-relational mapping which allows developers to work with relational databases. Entity Framework is an open-source framework. Read More...

You may read more on MVC, Web API and Angular

    Follow the below steps to create a Web API project in Visual Studio 2017

    Let's open the Visual Studio 2017 and start the demonstration.

    First, create a Web API project in Visual Studio 2017.
    Add ADO.Net Entity Data Model to this project.
    To do this follow the below steps.


    Web API2 CRUD operations using Entity Framework and MVC

    Select Approach.

    Web API2 CRUD operations using Entity Framework and MVC

    Set the connection string.

    Web API2 CRUD operations using Entity Framework and MVC

    Select the Entity Framework version.

    Select a database object you want to use.
    I am selecting ProductMaster table as I will demonstrate CRUD operation for Product Table.

    Web API2 CRUD operations using Entity Framework and MVC





    Build the project.

    Now add Web API 2 Controller with actions, using Entity Framework. 



    Web API2 CRUD operations using Entity Framework and MVC

    Select Model Class from dropdown and Data Context class as shown below.

    Web API2 CRUD operations using Entity Framework and MVC


    WebAPI2 controller code will look like this.


    namespace WebAPI2Demo.Controllers
    {
        public class ProductMastersController : ApiController
        {
            private ReviewAndShareEntities db = new ReviewAndShareEntities();

            // GET: api/ProductMasters
            public IQueryable<ProductMaster> GetProductMasters()
            {
                return db.ProductMasters;
            }

            // GET: api/ProductMasters/5
            [ResponseType(typeof(ProductMaster))]
            public IHttpActionResult GetProductMaster(int id)
            {
                ProductMaster productMaster = db.ProductMasters.Find(id);
                if (productMaster == null)
                {
                    return NotFound();
                }

                return Ok(productMaster);
            }

            // PUT: api/ProductMasters/5
            [ResponseType(typeof(void))]
            public IHttpActionResult PutProductMaster(int id, ProductMaster productMaster)
            {
                if (!ModelState.IsValid)
                {
                    return BadRequest(ModelState);
                }

                if (id != productMaster.id)
                {
                    return BadRequest();
                }

                db.Entry(productMaster).State = EntityState.Modified;

                try
                {
                    db.SaveChanges();
                }
                catch (DbUpdateConcurrencyException)
                {
                    if (!ProductMasterExists(id))
                    {
                        return NotFound();
                    }
                    else
                    {
                        throw;
                    }
                }

                return StatusCode(HttpStatusCode.NoContent);
            }

            // POST: api/ProductMasters
            [ResponseType(typeof(ProductMaster))]
            public IHttpActionResult PostProductMaster(ProductMaster productMaster)
            {
                if (!ModelState.IsValid)
                {
                    return BadRequest(ModelState);
                }

                db.ProductMasters.Add(productMaster);
                db.SaveChanges();

                return CreatedAtRoute("DefaultApi", new { id = productMaster.id }, productMaster);
            }

            // DELETE: api/ProductMasters/5
            [ResponseType(typeof(ProductMaster))]
            public IHttpActionResult DeleteProductMaster(int id)
            {
                ProductMaster productMaster = db.ProductMasters.Find(id);
                if (productMaster == null)
                {
                    return NotFound();
                }

                db.ProductMasters.Remove(productMaster);
                db.SaveChanges();

                return Ok(productMaster);
            }

            protected override void Dispose(bool disposing)
            {
                if (disposing)
                {
                    db.Dispose();
                }
                base.Dispose(disposing);
            }

            private bool ProductMasterExists(int id)
            {
                return db.ProductMasters.Count(e => e.id == id) > 0;
            }
        }
    }


    Host your web API in IIS and test.
    Open IIS and Add Website...




    Web API2 CRUD operations using Entity Framework and MVC




    Access the URL, you will see the result in XML format as shown below.



     To get a particular record, use below URL.
    /api/ProductMastsers/<id>



    Add a new project to consume Web API.
    To demonstrate, I will create ASP.Net MVC project.





    Web API2 CRUD operations using Entity Framework and MVC

    Select MVC from Project template.

    Web API2 CRUD operations using Entity Framework and MVC


    Add a productmodel class in MVC project


    Web API2 CRUD operations using Entity Framework and MVC

    ProductModel class.


    public class ProductModel
        {
            public int id { get; set; }
            public string product { get; set; }
            public decimal cost { get; set; }
            public int stock { get; set; }
        }



    Add Controller to your MVC application or you may use the existing one.

    Now add a view for your Action.



    Web API2 CRUD operations using Entity Framework and MVC

    Index View to show Product List.


    @model IEnumerable<WebAPI2Consumer.Models.ProductModel>

    @{
        ViewBag.Title = "Index";
    }

    <h2>Index</h2>

    <p>
        @Html.ActionLink("Create New", "Create")
    </p>
    <table class="table">
        <tr>
            <th>
                @Html.DisplayNameFor(model => model.product)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.cost)
            </th>
            <th>
                @Html.DisplayNameFor(model => model.stock)
            </th>
            <th></th>
        </tr>

    @foreach (var item in Model) {
        <tr>
            <td>
                @Html.DisplayFor(modelItem => item.product)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.cost)
            </td>
            <td>
                @Html.DisplayFor(modelItem => item.stock)
            </td>
            <td>
                @Html.ActionLink("Edit", "Edit", new { id=item.id }) |
                @Html.ActionLink("Details", "Details", new { id=item.id }) |
                @Html.ActionLink("Delete", "Delete", new { id=item.id })
            </td>
        </tr>
    }

    </table>



    In order to create a Web API client.
    Add Microsoft.AspNet.Webapi.Client using nuget package manager.






    Web API2 CRUD operations using Entity Framework and MVC

    Web API2 CRUD operations using Entity Framework and MVC

    Host you MVC project in IIS.

    Open IIS and Add a new website.

    Web API2 CRUD operations using Entity Framework and MVC


    If you don't want to host your application and web API in IIS.
    Right click on Solution name in visual studio 2017 solution explorer and select properties.
    Set Multiple startup projects for Web API and MVC project i.e. Web API consumer.


    Web API2 CRUD operations using Entity Framework and MVC



    In MVC ProductController, write below code and run your application you should get the list of products.


    public class ProductController : Controller
        {
            public static HttpClient webClient = new HttpClient();
            // GET: Product
            public ActionResult Index()
            {
                IEnumerable<ProductModel> products;
                HttpResponseMessage webResponse = webClient.GetAsync("http://localhost:90/api/ProductMasters").Result;
                products = webResponse.Content.ReadAsAsync<IEnumerable<ProductModel>>().Result;
                return View(products);
            }
        }


    Web API2 CRUD operations using Entity Framework and MVC


    Now, we will create a new record i.e. will do a post operation.
    Add an Action with name Create in ProductController.
    Add a View for Create action by selecting pa roper Model class from the dropdown. 


    Web API2 CRUD operations using Entity Framework and MVC


    Now click on Create New link on Product list view Page.
    Or access URL - /Product/Create
    Create Action in MVC Product Controller


    public ActionResult Create()
            {
                return View();
            }

            [HttpPost]
            public ActionResult Create(ProductModel productModel)
            {
                HttpResponseMessage httpResponseMessage = webClient.PostAsJsonAsync("http://localhost:90/api/ProductMasters", productModel).Result;
                return View();
            }

    Web API2 CRUD operations using Entity Framework and MVC

    Web API2 CRUD



    Now let’s update records.
    To do this, add a new action called Edit. Add a view -> Select Edit from the template and Model class.



    Web API2 CRUD operations using Entity Framework


    Edit action code will be like this.


    public ActionResult Edit()
            {
                return View();
            }


            [HttpPost]
            public ActionResult Edit(ProductModel productModel)
            {
                HttpResponseMessage httpResponseMessage = webClient.PutAsJsonAsync("http://localhost:90/api/ProductMasters/" + productModel.id, productModel).Result;
                return View();
            }

    Click on Edit button on Product list page.

    Web API2 CRUD operations using Entity Framework and MVC



    Make changes and Click on Save. Your record will be updated.
    You may change the button text and style as per your need.


    Web API2 CRUD operations using Entity Framework and MVC



    Now, we will create action to delete a record.



    public ActionResult Delete(int id)
            {
                HttpResponseMessage httpResponseMessage = webClient.DeleteAsync("http://localhost:90/api/ProductMasters/" + id).Result;
                return View();
            }

    Add a view for Delete action.


    Web API2 CRUD operations using Entity Framework and MVC

    Remove everything from Delete view and keep the following HTML content.


    @model WebAPI2Consumer.Models.ProductModel

    @{
        ViewBag.Title = "Delete";
    }

    <h2>Delete</h2>

    <div>
        <h4>ProductModel</h4>
        <hr />
         <h2>Record Deleted Successfully</h2>

        @using (Html.BeginForm()) {
            @Html.AntiForgeryToken()

            <div class="form-actions no-color">
              
                @Html.ActionLink("Back to List", "Index")
            </div>
        }
    </div>

    To view the details of a particular record, we need a separate action.
    Create an Action with name Details.


    public ActionResult Details(int id)
            {
                HttpResponseMessage httpResponse = webClient.GetAsync("http://localhost:90/api/ProductMasters/" + id).Result;
                return View(httpResponse.Content.ReadAsAsync<ProductModel>().Result);
            }
    Add a view for Details action. Select Details from Template and ProductModel from Model class.
    Click on Add.

    Web API2 CRUD operations using Entity Framework and MVC

    Click on Details link, you will see the details of that record.


    Comments

    Popular