پیاده سازی عملیات اصلی توسط Entity Framework در Asp.Net
شنبه 25 بهمن 1393در این مقاله میخواهیم عملیات حذف - ویرایش و اضافه کردن را با استفاده از Entity Framework در asp.net انجام دهیم
ابتدا یک جدول در پایگاه داده خود به شکل زیر بسازید:
سپس مقداری رکورد در آن درج کنید:
حال مراحل اضافه کردن مدل Entity به پروژه را به صورت تصویری نشان میدهیم:
در پنجره SolutionExplorer روی نام پرژه کلیک راست و گزینه Add New Item را انتخاب کنید و از پنجره باز شده سمت چب data را انتخاب و از لیست سمت راست ADO.NET Entity Data Model را انتخاب و در پایین پنجره نام را وارد کنید و سپس روی دکمه Add کلیک کنید:
حال باد اطلاعات server را وارد کنید و پایگاه داده خود را انتخاب کنید:
پس از انجام مراحل بالا مدل به پروژه اضافه شده و اماده استفاده می باشد حال صفحه Default.aspx خود را به شکل زیر تغییر دهید:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="CRUDUsingEntityFramework.Default" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <title>CRUD Operation Using Entity Framework In ASP.NET Grid View</title> </head> <body> <form id="form1" runat="server"> <div> <table style="border: solid 15px blue; width: 100%; vertical-align: central;"> <tr> <td style="padding-left: 20px; padding-top: 20px; padding-bottom: 20px; background-color: skyblue; font-family: 'Times New Roman'; font-size: 20pt; color: red;">CRUD Operation Using Entity Framework In ASP.NET Grid View </td> </tr> <tr> <td style="text-align: left;"> <asp:GridView ID="GVEmployee" runat="server" AutoGenerateColumns="False" ShowFooter="True" PageSize="10" AllowPaging="true" OnRowCommand="GVEmployee_RowCommand" DataKeyNames="Emp_ID" CellPadding="4" ForeColor="#333333" GridLines="None" OnRowCancelingEdit="GVEmployee_RowCancelingEdit" OnRowEditing="GVEmployee_RowEditing" OnRowUpdating="GVEmployee_RowUpdating" OnRowDeleting="GVEmployee_RowDeleting" OnPageIndexChanging="GVEmployee_OnPageIndexChanging"> <AlternatingRowStyle BackColor="White" /> <Columns> <asp:TemplateField HeaderText="Employee Name" HeaderStyle-HorizontalAlign="Left"> <EditItemTemplate> <asp:TextBox ID="txtEmpName" runat="server" Text='<%# Bind("Name") %>'></asp:TextBox> <asp:RequiredFieldValidator ID="valEmpName" runat="server" ControlToValidate="txtEmpName" Display="Dynamic" ErrorMessage="Employee Name is required." ForeColor="Red" SetFocusOnError="True" ValidationGroup="vldEditRecord">*</asp:RequiredFieldValidator> </EditItemTemplate> <ItemTemplate> <asp:Label ID="lblEmpName" runat="server" Text='<%# Bind("Name") %>'></asp:Label> </ItemTemplate> <FooterTemplate> <asp:TextBox ID="txtEmpNameNew" runat="server"></asp:TextBox> <asp:RequiredFieldValidator ID="valEmpNameNew" runat="server" ControlToValidate="txtEmpNameNew" Display="Dynamic" ErrorMessage="Employee Name is required." ForeColor="Red" SetFocusOnError="True" ValidationGroup="vldNewRecord">*</asp:RequiredFieldValidator> </FooterTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="Designation" HeaderStyle-HorizontalAlign="Left"> <EditItemTemplate> <asp:TextBox ID="txtDesignation" runat="server" Text='<%# Bind("Designation") %>'></asp:TextBox> <asp:RequiredFieldValidator ID="valDesignation" runat="server" ControlToValidate="txtDesignation" Display="Dynamic" ErrorMessage="Designation is required." ForeColor="Red" SetFocusOnError="True" ValidationGroup="vldEditRecord">*</asp:RequiredFieldValidator> </EditItemTemplate> <ItemTemplate> <asp:Label ID="lblDesignation" runat="server" Text='<%# Bind("Designation") %>'></asp:Label> </ItemTemplate> <FooterTemplate> <asp:TextBox ID="txtDesignationNew" runat="server"></asp:TextBox> <asp:RequiredFieldValidator ID="valDesignationNew" runat="server" ControlToValidate="txtDesignationNew" Display="Dynamic" ErrorMessage="Designation is required." ForeColor="Red" SetFocusOnError="True" ValidationGroup="vldNewRecord">*</asp:RequiredFieldValidator> </FooterTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="City" HeaderStyle-HorizontalAlign="Left"> <EditItemTemplate> <asp:TextBox ID="txtCity" runat="server" Text='<%# Bind("City") %>'></asp:TextBox> <asp:RequiredFieldValidator ID="valCity" runat="server" ControlToValidate="txtCity" Display="Dynamic" ErrorMessage="City is required." ForeColor="Red" SetFocusOnError="True" ValidationGroup="vldEditRecord">*</asp:RequiredFieldValidator> </EditItemTemplate> <ItemTemplate> <asp:Label ID="lblCity" runat="server" Text='<%# Bind("City") %>'></asp:Label> </ItemTemplate> <FooterTemplate> <asp:TextBox ID="txtCityNew" runat="server"></asp:TextBox> <asp:RequiredFieldValidator ID="valCityNew" runat="server" ControlToValidate="txtCityNew" Display="Dynamic" ErrorMessage="City is required." ForeColor="Red" SetFocusOnError="True" ValidationGroup="vldNewRecord">*</asp:RequiredFieldValidator> </FooterTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="State" HeaderStyle-HorizontalAlign="Left"> <EditItemTemplate> <asp:TextBox ID="txtState" runat="server" Text='<%# Bind("State") %>'></asp:TextBox> <asp:RequiredFieldValidator ID="valState" runat="server" ControlToValidate="txtState" Display="Dynamic" ErrorMessage="State is required." ForeColor="Red" SetFocusOnError="True" ValidationGroup="vldEditRecord">*</asp:RequiredFieldValidator> </EditItemTemplate> <ItemTemplate> <asp:Label ID="lblState" runat="server" Text='<%# Bind("State") %>'></asp:Label> </ItemTemplate> <FooterTemplate> <asp:TextBox ID="txtStateNew" runat="server"></asp:TextBox> <asp:RequiredFieldValidator ID="valStateNew" runat="server" ControlToValidate="txtStateNew" Display="Dynamic" ErrorMessage="State is required." ForeColor="Red" SetFocusOnError="True" ValidationGroup="vldNewRecord">*</asp:RequiredFieldValidator> </FooterTemplate> </asp:TemplateField> <asp:TemplateField HeaderText="Country" HeaderStyle-HorizontalAlign="Left"> <EditItemTemplate> <asp:TextBox ID="txtCountry" runat="server" Text='<%# Bind("Country") %>'></asp:TextBox> <asp:RequiredFieldValidator ID="valCountry" runat="server" ControlToValidate="txtCountry" Display="Dynamic" ErrorMessage="Country is required." ForeColor="Red" SetFocusOnError="True" ValidationGroup="vldEditRecord">*</asp:RequiredFieldValidator> </EditItemTemplate> <ItemTemplate> <asp:Label ID="lblCountry" runat="server" Text='<%# Bind("Country") %>'></asp:Label> </ItemTemplate> <FooterTemplate> <asp:TextBox ID="txtCountryNew" runat="server"></asp:TextBox> <asp:RequiredFieldValidator ID="valCountryNew" runat="server" ControlToValidate="txtCountryNew" Display="Dynamic" ErrorMessage="Country is required." ForeColor="Red" SetFocusOnError="True" ValidationGroup="vldNewRecord">*</asp:RequiredFieldValidator> </FooterTemplate> </asp:TemplateField> <asp:TemplateField HeaderText=""> <ItemTemplate> <asp:LinkButton ID="lnkEdit" runat="server" Text="" CommandName="Edit" ToolTip="Edit"> <img src="../Images/Edit.png" width="30px" /> </asp:LinkButton> <asp:LinkButton ID="lnkDelete" runat="server" Text="Delete" CommandName="Delete" ToolTip="Delete" OnClientClick='return confirm("Are you sure you want to delete employee record?");'> <img src="../Images/Delete.jpg" width="30px" /> </asp:LinkButton> </ItemTemplate> <EditItemTemplate> <asp:LinkButton ID="lnkInsert" runat="server" Text="" ValidationGroup="vldEditRecord" CommandName="Update" ToolTip="Save" OnClientClick='return confirm("Employee Record Saved Successfully.");'> <img src="../Images/Save2.jpg" width="30px" /> </asp:LinkButton> <asp:LinkButton ID="lnkCancel" runat="server" Text="" CommandName="Cancel" ToolTip="Cancel"> <img src="../Images/Cancel.jpg" width="30px" /> </asp:LinkButton> </EditItemTemplate> <FooterTemplate> <asp:LinkButton ID="lnkInsert" runat="server" Text="" ValidationGroup="vldNewRecord" CommandName="InsertNew" ToolTip="Add New Employee" OnClientClick='return confirm("Employee Record addedd Successfully.");'> <img src="../Images/Insert.jpg" width="30px" /> </asp:LinkButton> <asp:LinkButton ID="lnkCancel" runat="server" Text="" CommandName="CancelNew" ToolTip="Cancel"> <img src="../Images/Cancel.jpg" width="30px" /> </asp:LinkButton> </FooterTemplate> </asp:TemplateField> </Columns> <EditRowStyle BackColor="#2461BF" /> <FooterStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" /> <HeaderStyle BackColor="#507CD1" Font-Bold="True" ForeColor="White" /> <PagerStyle BackColor="#2461BF" ForeColor="White" HorizontalAlign="Center" /> <RowStyle BackColor="#EFF3FB" /> <SelectedRowStyle BackColor="#D1DDF1" Font-Bold="True" ForeColor="#333333" /> <SortedAscendingCellStyle BackColor="#F5F7FB" /> <SortedAscendingHeaderStyle BackColor="#6D95E1" /> <SortedDescendingCellStyle BackColor="#E9EBEF" /> <SortedDescendingHeaderStyle BackColor="#4870BE" /> </asp:GridView> </td> </tr> </table> </div> </form> </body> </html>
سپس در صفحه aspx.cs خود کد زیر را وارد کنید:
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace CRUDUsingEntityFramework { public partial class Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { BindGrid(); } } void BindGrid() { using (EmployeeManagementEntities context = new EmployeeManagementEntities()) { if (context.Employee.Count() > 0) { GVEmployee.DataSource = (from em in context.Employee select new { em.Emp_ID, em.Name, em.Designation, em.City, em.Country, em.State }).ToList(); GVEmployee.DataBind(); } else { GVEmployee.DataSource = null; GVEmployee.DataBind(); } } } protected void GVEmployee_OnPageIndexChanging(object sender, GridViewPageEventArgs e) { GVEmployee.PageIndex = e.NewPageIndex; BindGrid(); } protected void GVEmployee_RowCommand(object sender, GridViewCommandEventArgs e) { if (e.CommandName == "InsertNew") { GridViewRow row = GVEmployee.FooterRow; TextBox txtName = row.FindControl("txtEmpNameNew") as TextBox; TextBox txtDesignation = row.FindControl("txtDesignationNew") as TextBox; TextBox txtCity = row.FindControl("txtCityNew") as TextBox; TextBox txtState = row.FindControl("txtStateNew") as TextBox; TextBox txtCountry = row.FindControl("txtCountryNew") as TextBox; using (EmployeeManagementEntities context = new EmployeeManagementEntities()) { Employee obj = new Employee(); obj.Name = txtName.Text; obj.Designation = txtDesignation.Text; obj.City = txtCity.Text; obj.State = txtState.Text; obj.Country = txtCountry.Text; context.Employee.Add(obj); context.SaveChanges(); BindGrid(); } } } protected void GVEmployee_RowEditing(object sender, GridViewEditEventArgs e) { GVEmployee.EditIndex = e.NewEditIndex; BindGrid(); } protected void GVEmployee_RowCancelingEdit(object sender, GridViewCancelEditEventArgs e) { GVEmployee.EditIndex = -1; BindGrid(); } protected void GVEmployee_RowUpdating(object sender, GridViewUpdateEventArgs e) { GridViewRow row = GVEmployee.Rows[e.RowIndex]; TextBox txtName = row.FindControl("txtEmpName") as TextBox; TextBox txtDesignation = row.FindControl("txtDesignation") as TextBox; TextBox txtCity = row.FindControl("txtCity") as TextBox; TextBox txtState = row.FindControl("txtState") as TextBox; TextBox txtCountry = row.FindControl("txtCountry") as TextBox; using (EmployeeManagementEntities context = new EmployeeManagementEntities()) { int employeeID = Convert.ToInt32(GVEmployee.DataKeys[e.RowIndex].Value); Employee obj = context.Employee.First(x => x.Emp_ID == employeeID); obj.Name = txtName.Text; obj.Designation = txtDesignation.Text; obj.City = txtCity.Text; obj.State = txtState.Text; obj.Country = txtCountry.Text; context.SaveChanges(); GVEmployee.EditIndex = -1; BindGrid(); } } protected void GVEmployee_RowDeleting(object sender, GridViewDeleteEventArgs e) { int employeeID = Convert.ToInt32(GVEmployee.DataKeys[e.RowIndex].Value); using (EmployeeManagementEntities context = new EmployeeManagementEntities()) { Employee obj = context.Employee.First(x => x.Emp_ID == employeeID); context.Employee.Remove(obj); context.SaveChanges(); BindGrid(); } } } }
حالا میتونید برنامه رو اجرا کنید:
حال یک رکورد جدید اضافه کنید:
برای دیدن رکورد جدید به صفحه دوم برید:
حال یک رکورد را ویرایش کنید:
حال یک رکورد را حذف کنید:
- ASP.net
- 3k بازدید
- 11 تشکر