articles

Home / DeveloperSection / Articles / Model classes with Entity Framework in MVC

Model classes with Entity Framework in MVC

Chris Anderson 11707 05-Oct-2011

In this article, I am explaining how to use ASP.NET MVC with the Entity Framework. You learn how to use the Entity Wizard to create an ADO.NET Entity Data Model. I also illustrate how to select, insert, update, and delete database data by using the Entity Framework.


In order to use the Entity Framework, you need to create an Entity Data Model. For adding Entity Model:

1) Right click on Model Folder in the solution explorer.
2) Select Add
à New Item.

Model classes with Entity Framework in MVC

Select ADO.NET Entity Data Model from Add New Item template. You can change the name of Data Model with .edmx extension. Here I change it into ProductDb.edmx.

Model classes with Entity Framework in MVC

    Then Select Generate from Database option and Click on Next

Model classes with Entity Framework in MVC

Here you have to provide the connection string properties in a dialog box::
 1) Provide your server name.
 2) If you are using Windows mode do not provide Username and password else provide 
     both of them in the case of SQL Server Authentication.
 3) Select the database from the available list.

Model classes with Entity Framework in MVC

After establishing a new connection or selecting a database click on Next button to proceed.
Here I change name of entity connection setting as ProductDetails in Web.config.

Model classes with Entity Framework in MVC

Then select the table from the table list in the database as shown below. Here I am selection a product table for my application. After selecting a table clicks on Finish button.

Model classes with Entity Framework in MVC

The structures of my Product table in the database are as:

create table Product


(

   product_id int identity primary key,

   product_category varchar(20),

   product_name varchar(20),

   product_quantity int,

   product_price int

)

                         

After adding an entity model to have to add the Views in which you can select, update, insert or delete database records.
First add Index View that displays the list of product from the database. For adding View right click on Controller Index Action
à Select Add View.

Model classes with Entity Framework in MVC

When you select an Add View option, a dialog box will open. Select entity model class as our strongly typed view and List from Scaffold template.

Model classes with Entity Framework in MVC

You can modify a view (Index View) as I had modified below:

<html>


<head id="Head1" runat="server">

    <title>Index</title>

    <style type="text/css">

           table {

               font-family:Calibri;

               border-collapse:collapse;

           }

    </style>

</head>

<body>

    <p>

        <%: Html.ActionLink("Create New", "Create") %>

    </p>

    <table align="center" cellpadding="10" border="1px">

        <tr style="background-color:Aqua">

            <th></th>

            <th>Product ID</th>

            <th>Product Category</th>

            <th>Product Name</th>

            <th>Product Category</th>

            <th>Product Price</th>

        </tr>

 

    <% foreach (var item in Model) { %>

        <tr>

            <td>

               <%: Html.ActionLink("Edit", "Edit", new { id=item.product_id }) %> |

               <%: Html.ActionLink("Details", "Details", new { id=item.product_id }) %> |

               <%: Html.ActionLink("Delete", "Delete", new { id=item.product_id }) %>

            </td>

            <td>

                <%: item.product_id %>

            </td>

            <td>

                <%: item.product_category %>

            </td>

            <td>

                <%: item.product_name %>

            </td>

            <td>

                <%: item.product_quantity %>

            </td>

            <td>

                <%: item.product_price %>

            </td>

        </tr> 

    <% } %>

    </table>

</body>

</html>

 

Then add Edit View and this time select Edit option from Scaffold template list:

Model classes with Entity Framework in MVC

Edit View:
<html>


<head runat="server">

    <title>Edit</title>

    <style type="text/css">

         div

         {

             font-family:Calibri;

         }

    </style>

</head>

<body>

    <script src="<%: Url.Content("~/Scripts/jquery-1.4.4.min.js") %>"  
    type="text/javascript"></script>

    <script src="<%: Url.Content("~/Scripts/jquery.validate.min.js") %>" 
    type="text/javascript"></script>

    <script src="<%: Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js") %>" 
    type="text/javascript"></script>

 

    <% using (Html.BeginForm()) { %>

        <%: Html.ValidationSummary(true) %>

        <fieldset>

            <legend>Product</legend>

            <br />

 

            <%: Html.HiddenFor(model => model.product_id) %>

 

            <div class="editor-label">

                <b><%: Html.LabelFor(model => model.product_category) %></b>

            </div>

            <div class="editor-field">

                <%: Html.EditorFor(model => model.product_category) %>

                <%: Html.ValidationMessageFor(model => model.product_category) %>

            </div><br />

 

            <div class="editor-label">

                <b><%: Html.LabelFor(model => model.product_name) %></b>

            </div>

            <div class="editor-field">

                <%: Html.EditorFor(model => model.product_name) %>

                <%: Html.ValidationMessageFor(model => model.product_name) %>

            </div><br />

 

            <div class="editor-label">

                <b><%: Html.LabelFor(model => model.product_quantity) %></b>

            </div>

            <div class="editor-field">

                <%: Html.EditorFor(model => model.product_quantity) %>

                <%: Html.ValidationMessageFor(model => model.product_quantity) %>

            </div><br />

 

            <div class="editor-label">

                <b><%: Html.LabelFor(model => model.product_price) %></b>

            </div>

            <div class="editor-field">

                <%: Html.EditorFor(model => model.product_price) %>

                <%: Html.ValidationMessageFor(model => model.product_price) %>

            </div><br />

 

            <p>

                <input type="submit" value="Save" />

            </p>

        </fieldset>

    <% } %>

 

    <div>

        <%: Html.ActionLink("Back to List", "Index") %>

    </div>

</body>

</html>
 

Add Details View and select Details option from Scaffold template list:

Model classes with Entity Framework in MVC

Details View:
<html>


<head runat="server">

    <title>Details</title>

        <style type="text/css">

         div {

             font-family:Calibri;

         }

    </style>

</head>

<body>

    <fieldset>

        <legend>Product</legend>

        <br />

        <div class="display-label"><b>Product Category</b></div>

        <div class="display-field"><%: Model.product_category %></div><br />



        <div class="display-label"><b>Product Name</b></div>

        <div class="display-field"><%: Model.product_name %></div><br />



        <div class="display-label"><b>Product Quantity</b></div>

        <div class="display-field"><%: Model.product_quantity %></div><br />



        <div class="display-label"><b>Product Price</b></div>

        <div class="display-field"><%: Model.product_price %></div><br />

    </fieldset>

    <p>



        <%: Html.ActionLink("Edit", "Edit", new { id=Model.product_id }) %> |

        <%: Html.ActionLink("Back to List", "Index") %>

    </p>

</body>

</html>

 

Add Delete View and select Delete option from Scaffold template list:

Model classes with Entity Framework in MVC

Delete View:
<html>


<head id="Head1" runat="server">

    <title>Delete</title>

    <style type="text/css">

         div

         {

             font-family:Calibri;

         }

    </style>

</head>

<body>

    <h3>Are you sure you want to delete this?</h3>

    <fieldset>

        <legend>Product</legend>

        <br />



        <div class="display-label"><b>Product Category</b></div>

        <div class="display-field"><%: Model.product_category %></div><br />



        <div class="display-label"><b>Product Name</b></div>

        <div class="display-field"><%: Model.product_name %></div><br />



        <div class="display-label"><b>Product Quantity</b></div>

        <div class="display-field"><%: Model.product_quantity %></div><br />



        <div class="display-label"><b>Product Price</b></div>

        <div class="display-field"><%: Model.product_price %></div><br />

    </fieldset>

    <% using (Html.BeginForm()) { %>

        <p>

            <input type="submit" value="Delete" /> |

            <%: Html.ActionLink("Back to List", "Index") %>

        </p>

    <% } %>



</body>

</html>

 

Model classes with Entity Framework in MVC

Create View:
<html>


<head id="Head1" runat="server">

    <title>Create</title>

   <style type="text/css">

         div

         {

             font-family:Calibri;

         }

    </style>

</head>

<body>

    <script src="<%: Url.Content("~/Scripts/jquery-1.4.4.min.js") %>"
    type="text/javascript"></script>

    <script src="<%: Url.Content("~/Scripts/jquery.validate.min.js") %>"
    type="text/javascript"></script>

    <script src="<%: Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js") %>"
    type="text/javascript"></script>



    <% using (Html.BeginForm()) { %>

        <%: Html.ValidationSummary(true) %>

        <fieldset>

            <legend>Product</legend>

            <br />



            <div class="editor-label">

                <b><%: Html.LabelFor(model => model.product_category) %></b>

            </div>

            <div class="editor-field">

                <%: Html.EditorFor(model => model.product_category) %>

                <%: Html.ValidationMessageFor(model => model.product_category) %><br />

            </div>



            <div class="editor-label">

                <b><%: Html.LabelFor(model => model.product_name) %></b>

            </div>

            <div class="editor-field">

                <%: Html.EditorFor(model => model.product_name) %>

                <%: Html.ValidationMessageFor(model => model.product_name) %><br />

            </div>



            <div class="editor-label">

                <b><%: Html.LabelFor(model => model.product_quantity) %></b>

            </div>

            <div class="editor-field">

                <%: Html.EditorFor(model => model.product_quantity) %>

                <%: Html.ValidationMessageFor(model => model.product_quantity) %><br />

            </div>



            <div class="editor-label">

                <b><%: Html.LabelFor(model => model.product_price) %></b>

            </div>

            <div class="editor-field">

                <%: Html.EditorFor(model => model.product_price) %>

                <%: Html.ValidationMessageFor(model => model.product_price) %><br />

            </div>



            <p>

                <input type="submit" value="Create" />

            </p>

        </fieldset>

    <% } %>



    <div>

        <%: Html.ActionLink("Back to List", "Index") %>

    </div>

</body>

</html>

 

After adding the Views, in the Controller we have to call the Views.

1) The Index() action returns all of the product records from database table with the help  of the Entity Framework.
2) The First Edit() action returns selected product detail and second one update the record   in the database.
3) The Details() action returns the details of the selected product.
4) The first Create() action provide you a form in which you can insert the product details  and second one create a new record in the database table.
5) The first Delete() action ask you for a confirmation of delete and second one delete the   records from the table.

using System;


using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

using ExDetailsMVC.Models;



namespace ExDetailsMVC.Controllers

{

    public class HomeController : Controller

    {

        ProductDetails product = new ProductDetails();



        public ActionResult Index()

        {

            return View(product.Products.ToList());

        }



        public ActionResult Edit(int id)

        {

            return View(product.Products.Where(m => m.product_id == id).Single());

        }



        [HttpPost]

        public ActionResult Edit(FormCollection form)

        {

          var id = Int32.Parse(form[0]);

          var productToUpdate = product.Products.First(m => m.product_id == id);



          TryUpdateModel(productToUpdate, new string[] { "product_category",
          "product_name", "product_quantity", "product_price" }, form.ToValueProvider());



            if (ModelState.IsValid)

            {

                product.SaveChanges();

                return RedirectToAction("Index", "Home");

            }

            return View(productToUpdate);

        }

        public ActionResult Details(int id)

        {

            return View(product.Products.Where(m => m.product_id == id).Single());

        }



        public ActionResult Delete(int id)

        {

            return View(product.Products.Where(m => m.product_id == id).Single());

        }

        [HttpPost]

        public ActionResult Delete(int id, Product prd)

        {

            var productToDelete = (from m in product.Products where m.product_id == id
            select m).FirstOrDefault();

            product.DeleteObject(productToDelete);

            product.SaveChanges();

            return RedirectToAction("Index", "Home");

        }



        public ActionResult Create()

        {

            return View();

        }

        [HttpPost]

        public ActionResult Create(Product prd)

        {

            if (ModelState.IsValid)

            {

                product.AddToProducts(prd);

                product.SaveChanges();

                return RedirectToAction("Index", "Home");

            }

            else

                return View();

        }

    }

}

 

After creating a Controller, you can see the output in your browser:

Model classes with Entity Framework in MVC

By using above code and information you can easily understand how to select, insert, delete and update the database records with the entity framework in MVC.


Updated 08-Nov-2019
hi I am software developer at mindstick software pvt. ltd.

Leave Comment

Comments

Liked By