Simple Shopping Cart Using Entity Framework in ASP.Net

This article explains Entity Framework in ASP.NET and shows how to create a shopping cart using it.

In this article you will learn:

  • Overview of Entity Framework
  • Enter only numeric quantity value in TextBox
  • Calculate price and quantity in the third column.
  • Calculate Total Amount of the cart if any quantity is updated

Overview Of Entity Framework

"The Microsoft ADO.NET Entity Framework is an Object/Relational Mapping (ORM) framework that enables developers to work with relational data as domain-specific objects, eliminating the need for most of the data access plumbing code that developers usually need to write.

Using the Entity Framework, developers issue queries using LINQ, then retrieve and manipulate data as strongly typed objects.

The Entity Framework’s ORM implementation provides services like change tracking, identity resolution, lazy loading, and query translation so that developers can focus on their application-specific business logic rather than the data access fundamentals.”

For more details you can visit this site: entityframework

Step 1: Create the table using this Stored Procedure in your database.

Creating table 'ProductDetails'

  1. CREATE TABLE [dbo].[ProductDetails] (  
  2. [ProductId] decimal(18,0) IDENTITY(1,1) NOT NULL,  
  3. [ProductName] nvarchar(50) NULL,  
  4. [ProductQty] decimal(18,0) NULL,  
  5. [ProductRate] decimal(18,0) NULL,  
  6. [ProductShippingAddress] nvarchar(maxNULL,  
  7. [CreatedDate] datetime NULL  
  8. );  
  9. GO  

Step 2: Enter your GridView details in the client-side.

for edit button  (.aspx code)

  1. <asp:TemplateField>  
  2.       <ItemTemplate>  
  3.          <asp:ImageButton ID="btnEdit" runat="server" CommandName="Edit" CommandArgument='<%# Eval("ProductId") %>'  
  4.                  ImageUrl="~/Image/Edit.jpg" Height="50px" Width="50px" OnCommand="btnEdit_Command"  
  5.                                                       CausesValidation="false" />  
  6.            </ItemTemplate>   
  7. </asp:TemplateField>  
for Delete button (.aspx code)
  1. <asp:TemplateField>  
  2.         <ItemTemplate>  
  3.                <asp:ImageButton ID="btnDelete" runat="server" CommandName="Delete" CommandArgument='<%# Eval("ProductId") %>'  
  4.                         ImageUrl="~/Image/delete.png" Height="50px" Width="50px" OnCommand="btnDelete_Command"  
  5.                                                         CausesValidation="false" />  
  6.           </ItemTemplate>  
  7. </asp:TemplateField>  
For a numeric value you can implement this validation expression:
  1. <asp:RegularExpressionValidator ID="RegularExpressionValidator1" runat="server" ErrorMessage="Please Enter Your Product Rate(Only Numeric Value Allow)"  ControlToValidate="Enter Your ID" ForeColor="Red" ValidationExpression="^[0-9]+$" >
  2.  </asp:RegularExpressionValidator>   

Step 3: Create the ADO.NET Entity Data Model.

In order to use the Entity Framework, you need to create an Entity Data Model. You can take advantage of the Visual Studio Entity Data Model Wizard to generate an Entity Data Model from a database automatically.

Use the following procedure:

  1. Right-click the Models folder in the Solution Explorer window and select the menu options "Add" -> "New Item".

  2. In the Add New Item dialog, select the Data category.

  3. Select the ADO.NET Entity Data Model template, give the Entity Data Model the name “YourDatebase.edmx”, and click the Add button. Clicking the Add button launches the Data Model Wizard.

  4. In the Choose Model Contents step, choose the Generate from a database option and click the Next button.

  5. In the Choose Your Data Connection step, select the “YourDatebase.edmx”, database connection, enter the entities connection settings name YourDatebaseEntities, and click the Next button.

  6. In the Choose Your Database Objects step, select the Your database table and click the Finish button.    
Change your web.config file  
  1. <add name="ProductProjectEntities" connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=System.Data.SqlClient;provider connection string="data source=yoursource;initial catalog=ProductProject;persist security info=True;user id=aa;password=aaa;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />  
Step 4: Bind Your GridView
  1.  //Generate Public Entities  
  3. readonly  ProductProjectEntities _ent = new ProductProjectEntities();  
  5.     //GridView Binding  
  6.         public void BindProductGridview()  
  7.         {  
  8.             try  
  9.             {  
  10.                 var _pd = from p in _ent.ProductDetails  
  11.                           select p;  
  12.                 if (_pd.Count() > 0)  
  13.                 {  
  14.                     GvProduct.DataSource = _pd.ToList();  
  15.                     GvProduct.DataBind();  
  16.                 }  
  17.             }  
  18.             catch (Exception ex)  
  19.             {  
  20.                 throw ex;  
  21.             }  
  22.         }  

Step 5: Calculate the product total price based on the entered quantity.

You can implement this code in the RowDataBound Event in the Gridview Control.

Using this event we can find the specific controls, such as Label, TextBox, dropdown, checkbox and get values from controls inside the GridView control.

  1. protected void GvProduct_RowDataBound(object sender, GridViewRowEventArgs e)  
  2.         {  
  3.             try  
  4.             {  
  5.                 if (e.Row.RowType == DataControlRowType.DataRow)  
  6.                 {  
  7.                     decimal _Price = 0;  
  8.                     decimal _Quantity = 0;  
  9.                     decimal _TotalAmmount = 0;  
  11.                     _Price = Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "ProductRate"));  
  12.                     _Quantity = Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "ProductQty"));  
  13.                     _TotalAmmount = _Price * _Quantity;  
  15.                     Label _lblAmmount = (Label)e.Row.Cells[0].FindControl("lblAmmount");  
  16.                     _lblAmmount.Text = _TotalAmmount.ToString();  
  17.                     _TotalAmmountLast = decimal.Parse(_TotalAmmountLast.ToString()) + _TotalAmmount;  
  18.                 }  
  20.                 // below code for calculate Grand total in footer template and display also.....   
  21.                 if (e.Row.RowType == DataControlRowType.Footer)  
  22.                 {  
  23.                     Label _txtTotal = (Label)e.Row.Cells[0].FindControl("lblTotalAmmount");  
  24.                     _txtTotal.Text = _TotalAmmountLast.ToString();  
  25.                 }  
  26.             }  
  27.             catch (Exception ex)  
  28.             {  
  29.                 throw ex;  
  30.             }  
  31.         } 
Step 6: This is the final step of our application.
shopping cart Overview 
Test Output Here.

Up Next
    Ebook Download
    View all
    View all