ASP.NET從零開始學習EF的增刪改查
最近辭職了,但是離真正的離職還有一段時間,趁着這段空檔期,總想着寫些東西,想來想去,也不是很明確到底想寫個啥,但是閑着也是夠無聊的。思前想后,今天決定寫一個簡單的EF的增刪改查給大家吧。本次教程,盡量少用控件,盡量做到,純HTML+JS+后台代碼。
好了,廢話不說了,能看到這篇文章的,應該都是想知道EF的一些增刪改查的操作,所以,應該也是知道EF的一些優點。鑒於也有可能有新手可能第一次使用,我就簡略講一下他的優點。EF的優點,本次講到的就是,他對數據庫的操作集成的非常簡單,對指定的表操作的話,只需要一個簡單的add或者remove即可,非常簡潔。好下面就按着教程來,一步一步往下走。
這次,我們用的是DB first模式。
一、首先要做的事情,就是新建數據庫了,這次我們用到的數據庫名為:
Student,表明為:User,下面的是數據庫的生成操作:
USE [master]GO/****** Object: Database [Student] Script Date: 05/20/2016 11:36:27 ******/CREATE DATABASE [Student] ON PRIMARY( NAME = N'Student', FILENAME = N'F:\Jeffrey9061\SVN\DB\Student.mdf' , SIZE = 3072KB , MAXSIZE = UNLIMITED, FILEGROWTH = 1024KB )LOG ON( NAME = N'Student_log', FILENAME = N'F:\Jeffrey9061\SVN\DB\Student_log.ldf' , SIZE = 1024KB , MAXSIZE = 2048GB , FILEGROWTH = 10%)GOALTER DATABASE [Student] SET COMPATIBILITY_LEVEL = 100GOIF (1 = FULLTEXTSERVICEPROPERTY('IsFullTextInstalled'))beginEXEC [Student].[dbo].[sp_fulltext_database] @action = 'enable'endGOALTER DATABASE [Student] SET ANSI_NULL_DEFAULT OFFGOALTER DATABASE [Student] SET ANSI_NULLS OFFGOALTER DATABASE [Student] SET ANSI_PADDING OFFGOALTER DATABASE [Student] SET ANSI_WARNINGS OFFGOALTER DATABASE [Student] SET ARITHABORT OFFGOALTER DATABASE [Student] SET AUTO_CLOSE OFFGOALTER DATABASE [Student] SET AUTO_CREATE_STATISTICS ONGOALTER DATABASE [Student] SET AUTO_SHRINK OFFGOALTER DATABASE [Student] SET AUTO_UPDATE_STATISTICS ONGOALTER DATABASE [Student] SET CURSOR_CLOSE_ON_COMMIT OFFGOALTER DATABASE [Student] SET CURSOR_DEFAULT GLOBALGOALTER DATABASE [Student] SET CONCAT_NULL_YIELDS_NULL OFFGOALTER DATABASE [Student] SET NUMERIC_ROUNDABORT OFFGOALTER DATABASE [Student] SET QUOTED_IDENTIFIER OFFGOALTER DATABASE [Student] SET RECURSIVE_TRIGGERS OFFGOALTER DATABASE [Student] SET DISABLE_BROKERGOALTER DATABASE [Student] SET AUTO_UPDATE_STATISTICS_ASYNC OFFGOALTER DATABASE [Student] SET DATE_CORRELATION_OPTIMIZATION OFFGOALTER DATABASE [Student] SET TRUSTWORTHY OFFGOALTER DATABASE [Student] SET ALLOW_SNAPSHOT_ISOLATION OFFGOALTER DATABASE [Student] SET PARAMETERIZATION SIMPLEGOALTER DATABASE [Student] SET READ_COMMITTED_SNAPSHOT OFFGOALTER DATABASE [Student] SET HONOR_BROKER_PRIORITY OFFGOALTER DATABASE [Student] SET READ_WRITEGOALTER DATABASE [Student] SET RECOVERY FULLGOALTER DATABASE [Student] SET MULTI_USERGOALTER DATABASE [Student] SET PAGE_VERIFY CHECKSUMGOALTER DATABASE [Student] SET DB_CHAINING OFFGOEXEC sys.sp_db_vardecimal_storage_format N'Student', N'ON'GOUSE [Student]GO/****** Object: Table [dbo].[User] Script Date: 05/20/2016 11:36:27 ******/SET ANSI_NULLS ONGOSET QUOTED_IDENTIFIER ONGOCREATE TABLE [dbo].[User]([ID] [int] IDENTITY(1,1) NOT NULL,[Name] [nvarchar](50) NULL,[Age] [int] NULL,[Sex] [nvarchar](50) NULL,CONSTRAINT [PK_User] PRIMARY KEY CLUSTERED([ID] ASC)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]) ON [PRIMARY]GO二、新建一個asp.net的Web站點,命名為: LMX.EF.Web ,如下圖:![]()
選擇空模板
二、添加EF的ADO.NET實體數據模型 ,如下圖:
命名為:Student
點擊:新建連接
填寫本地SQL數據庫的鏈接,然后選擇:Student數據庫,如下:
點擊“確定”
點擊:“下一步”
選擇“6.x”,這里,如果你們用的是VS2013,選“5.0”也一樣。
然后點擊“完成”。如下圖:
添加實體類數據模型到此結束。三、添加增刪改查頁面。1,增加add.aspx![]()
2,修改edit.aspx3,列表list.aspx(包含搜索和刪除)四、代碼實現add.aspx 前端:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="add.aspx.cs" Inherits="LMX.EF.Web.add" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>增加用戶</title> <script src="js/jquery-1.8.3.min.js"></script> <style type="text/css"> /* 表格的樣式*/ .tab { border-collapse: collapse; padding-top: 10px; padding-left: 0px; padding-right: 0px; margin: 0px; border: 1px solid #BDBCBC; } .tr { border-collapse: collapse; height: 30px; } .td { background-color: #fff; font-size: 14px; font-family: "微軟雅黑"; text-align: center; border-right: 1px solid #BDBCBC; border-bottom: 1px dashed #BDBCBC; } </style> <script type="text/javascript"> $(function () { $("#btnSubmit").click(function () { var vData = $("#form1").serialize(); $.ajax({ type: 'get', url: location.href + "?type=add", data: vData, success: function (msg) { alert(msg); } }) }); $("#btnList").click(function () { window.location.href = "list.aspx"; }); }) </script> </head> <body> <form id="form1"> <table class="tab"> <tr class="tr"> <td class="td">姓名</td> <td class="td"> <input type="text" name="Name" /> </td> </tr> <tr class="tr"> <td class="td">年齡</td> <td class="td"> <input type="text" name="Age" /> </td> </tr> <tr class="tr"> <td class="td">性別</td> <td class="td"> <input type="text" name="Sex" /> </td> </tr> <tr class="tr"> <td class="td"> <input type="button" id="btnList" value="返回列表" /> </td> <td class="td"> <input type="button" id="btnSubmit" value="確認提交" /> </td> </tr> </table> </form> </body> </html>
后端:using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace LMX.EF.Web { public partial class add : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { if (Request.QueryString["type"] == "add") { string strName = Request.QueryString["Name"]; string strAge = Request.QueryString["Age"]; string strSex = Request.QueryString["Sex"]; using (StudentEntities ent = new StudentEntities()) { User aNewUser = new User() { Age = 20, Name = strName, Sex = strSex }; ent.User.Add(aNewUser); if (ent.SaveChanges() > 0) { Response.Write("添加成功。"); } else { Response.Write("添加失敗。"); } Response.End(); } } } } } }
list.aspx 前端:<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="list.aspx.cs" Inherits="LMX.EF.Web.list" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>列表</title> <script src="js/jquery-1.8.3.min.js"></script> <style type="text/css"> /* 表格的樣式*/ .tab { border-collapse: collapse; padding-top: 10px; padding-left: 0px; padding-right: 0px; margin: 0px; border: 1px solid #BDBCBC; } .tr { border-collapse: collapse; height: 30px; } .td { background-color: #fff; font-size: 14px; font-family: "微軟雅黑"; text-align: center; border-right: 1px solid #BDBCBC; border-bottom: 1px dashed #BDBCBC; } </style> <script type="text/javascript"> $(function () { loadData(); //編輯用戶 $("#btnEdit").click(function () { var vID = $("#UserID").val(); if (vID == "" || vID == null) { alert("請輸入用戶編號。"); return; } window.location.href = "edit.aspx?id=" + vID; }); //刪除用戶 $("#btnDel").click(function () { var vID = $("#UserID").val(); if (vID == "" || vID == null) { alert("請輸入用戶編號。"); return; } $.ajax({ type: 'post', url: location.href + "?type=del&&id="+vID, success: function (data) { alert(data); loadData(); } }) }); //繼續添加 $("#btnAdd").click(function () { window.location.href = "add.aspx"; }); }) //獲取用戶列表 function loadData() { var vHead = "<tr class=\"tr\"><td class=\"td\">編號</td><td class=\"td\">姓名</td><td class=\"td\">年齡</td><td class=\"td\">性別</td></tr>"; $.ajax({ type: 'get', url: location.href + "?type=loadData", success: function (data) { if (data != null) { data = JSON.parse(data); for (var i = 0; i < data.length; i++) { vHead += "<tr class=\"tr\"><td class=\"td\">" + data[i].ID + "</td><td class=\"td\">" + data[i].Name + "</td><td class=\"td\">" + data[i].Age + "</td><td class=\"td\">" + data[i].Sex + "</td></tr>"; } } $("#tabList").html(vHead); } }) } </script> </head> <body> <table class="tab" id="tabList"> <tr class="tr"> <td class="td">編號</td> <td class="td">姓名</td> <td class="td">年齡</td> <td class="td">性別</td> </tr> </table> <br /> <input type="button" id="btnAdd" value="繼續添加" /> <br /> 用戶編號:<input type="text" id="UserID" /><input type="button" id="btnEdit" value="編輯" /><input type="button" id="btnDel" value="刪除" /> </body> </html>
后端:using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Script.Serialization; using System.Web.UI; using System.Web.UI.WebControls; namespace LMX.EF.Web { public partial class list : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { if (Request.QueryString["type"] == "loadData") { using (StudentEntities ent = new StudentEntities()) { List<User> userList = ent.User.ToList(); JavaScriptSerializer js = new JavaScriptSerializer(); string strJsonData = js.Serialize(userList); Response.Write(strJsonData); Response.End(); } } if (Request.QueryString["type"] == "del") { string strID = Request.QueryString["id"]; int iID = int.Parse(strID); using (StudentEntities ent = new StudentEntities()) { User aUser = (from c in ent.User where c.ID == iID select c).FirstOrDefault(); if (aUser != null) { ent.User.Remove(aUser); if (ent.SaveChanges() > 0) { Response.Write("刪除成功。"); } else { Response.Write("刪除失敗。"); } } else { Response.Write("不存在此用戶,請確認用戶ID是否正確。"); } Response.End(); } } } } } }
edit.aspx 前端:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="edit.aspx.cs" Inherits="LMX.EF.Web.edit" %> <!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head runat="server"> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>編輯</title> <script src="js/jquery-1.8.3.min.js"></script> <script type="text/javascript"> $(function () { $("#btnList").click(function () { window.location.href = "list.aspx"; }); }) </script> </head> <body> <form id="form1" runat="server"> <table class="tab"> <tr class="tr"> <td class="td">姓名</td> <td class="td"> <asp:TextBox ID="Name" runat="server"></asp:TextBox> <asp:TextBox ID="id" runat="server" Visible="False"></asp:TextBox> </td> </tr> <tr class="tr"> <td class="td">年齡</td> <td class="td"> <asp:TextBox ID="Age" runat="server"></asp:TextBox> </td> </tr> <tr class="tr"> <td class="td">性別</td> <td class="td"> <asp:TextBox ID="Sex" runat="server"></asp:TextBox> </td> </tr> <tr class="tr"> <td class="td"> <input type="button" id="btnList" value="返回列表" /> </td> <td class="td"> <asp:Button ID="btnSubmit" runat="server" Text="確認提交" OnClick="btnSubmit_Click" /> </td> </tr> </table> </form> </body> </html>
后端:using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.UI; using System.Web.UI.WebControls; namespace LMX.EF.Web { public partial class edit : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { string strID = Request.QueryString["id"]; int iID = int.Parse(strID); using (StudentEntities ent = new StudentEntities()) { User aUser = (from c in ent.User where c.ID == iID select c).FirstOrDefault(); if (aUser != null) { Name.Text = aUser.Name; Age.Text = aUser.Age.ToString(); Sex.Text = aUser.Sex; id.Text = strID; } } } } /// <summary> /// 提交修改 /// </summary> /// <param name="sender"></param> /// <param name="e"></param> protected void btnSubmit_Click(object sender, EventArgs e) { string strName = Name.Text; string strAge = Age.Text; string strSex = Sex.Text; string strID = id.Text; int iID = int.Parse(strID); using (StudentEntities ent = new StudentEntities()) { User aUser = (from c in ent.User where c.ID == iID select c).FirstOrDefault(); if (aUser != null) { aUser.Name = strName; aUser.Age = 20; aUser.Sex = strSex; if (ent.SaveChanges() > 0) { Response.Write("<script>alert('修改成功。')</script>"); } } } } } }
到這里,就大功告成啦,接下來的東西,就由大家自己去展開拓展了,本次經驗分享到此結束,如果覺得寫得不錯,或者對你有幫助,請點“好文要頂”或者“關注我”, 轉載請保留原作者地址以及姓名 。我新建一個QQ群,如果有問題,可以在群里提。如果合適,也會根據大家提的比較多的問題,來寫篇博文,幫助更多的人,群號:275523437點擊鏈接加入群【.Net,MVC,EasyUI,MUI,Html,JS】: http://jq.qq.com/?_wv=1027&k=2A0RbLd(如果有私活,或者一起合作的,也可以私信找我呀,嘿嘿);作者:南宮蕭塵E-mail:314791147@qq.comQQ:314791147日期:2016-05-20




