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'
- CREATE TABLE [dbo].[ProductDetails] (
- [ProductId] decimal(18,0) IDENTITY(1,1) NOT NULL,
- [ProductName] nvarchar(50) NULL,
- [ProductQty] decimal(18,0) NULL,
- [ProductRate] decimal(18,0) NULL,
- [ProductShippingAddress] nvarchar(max) NULL,
- [CreatedDate] datetime NULL
- );
- GO
Step 2: Enter your GridView details in the client-side.
for edit button (.aspx code)
- <asp:TemplateField>
- <ItemTemplate>
- <asp:ImageButton ID="btnEdit" runat="server" CommandName="Edit" CommandArgument=
- ImageUrl="~/Image/Edit.jpg" Height="50px" Width="50px" OnCommand="btnEdit_Command"
- CausesValidation="false" />
- </ItemTemplate>
- </asp:TemplateField>
for Delete button (.aspx code)
- <asp:TemplateField>
- <ItemTemplate>
- <asp:ImageButton ID="btnDelete" runat="server" CommandName="Delete" CommandArgument=
- ImageUrl="~/Image/delete.png" Height="50px" Width="50px" OnCommand="btnDelete_Command"
- CausesValidation="false" />
- </ItemTemplate>
- </asp:TemplateField>
For a numeric value you can implement this validation expression:
- <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]+$" >
- </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:
- Right-click the Models folder in the Solution Explorer window and select the menu options "Add" -> "New Item".
- In the Add New Item dialog, select the Data category.
- 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.
- In the Choose Model Contents step, choose the Generate from a database option and click the Next button.
- 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.
- In the Choose Your Database Objects step, select the Your database table and click the Finish button.
Change your web.config file
- <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
-
-
- readonly ProductProjectEntities _ent = new ProductProjectEntities();
-
-
- public void BindProductGridview()
- {
- try
- {
- var _pd = from p in _ent.ProductDetails
- select p;
- if (_pd.Count() > 0)
- {
- GvProduct.DataSource = _pd.ToList();
- GvProduct.DataBind();
- }
- }
- catch (Exception ex)
- {
- throw ex;
- }
- }
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.
- protected void GvProduct_RowDataBound(object sender, GridViewRowEventArgs e)
- {
- try
- {
- if (e.Row.RowType == DataControlRowType.DataRow)
- {
- decimal _Price = 0;
- decimal _Quantity = 0;
- decimal _TotalAmmount = 0;
-
- _Price = Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "ProductRate"));
- _Quantity = Convert.ToDecimal(DataBinder.Eval(e.Row.DataItem, "ProductQty"));
- _TotalAmmount = _Price * _Quantity;
-
- Label _lblAmmount = (Label)e.Row.Cells[0].FindControl("lblAmmount");
- _lblAmmount.Text = _TotalAmmount.ToString();
- _TotalAmmountLast = decimal.Parse(_TotalAmmountLast.ToString()) + _TotalAmmount;
- }
-
-
- if (e.Row.RowType == DataControlRowType.Footer)
- {
- Label _txtTotal = (Label)e.Row.Cells[0].FindControl("lblTotalAmmount");
- _txtTotal.Text = _TotalAmmountLast.ToString();
- }
- }
- catch (Exception ex)
- {
- throw ex;
- }
- }
Step 6: This is the final step of our application.
Output