http://www.cnblogs.com/nangong/p/db29669e2c6d72fb3d0da947280aa1ce.html
最近上班空閑,趁着有這段空檔期,總想着寫些東西,但是閑着也是夠無聊的。思前想后,今天決定寫一個簡單的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%) GO ALTER DATABASE [Student] SET COMPATIBILITY_LEVEL = 100 GO IF (1 = FULLTEXTSERVICEPROPERTY('IsFullTextInstalled')) begin EXEC [Student].[dbo].[sp_fulltext_database] @action = 'enable' end GO ALTER DATABASE [Student] SET ANSI_NULL_DEFAULT OFF GO ALTER DATABASE [Student] SET ANSI_NULLS OFF GO ALTER DATABASE [Student] SET ANSI_PADDING OFF GO ALTER DATABASE [Student] SET ANSI_WARNINGS OFF GO ALTER DATABASE [Student] SET ARITHABORT OFF GO ALTER DATABASE [Student] SET AUTO_CLOSE OFF GO ALTER DATABASE [Student] SET AUTO_CREATE_STATISTICS ON GO ALTER DATABASE [Student] SET AUTO_SHRINK OFF GO ALTER DATABASE [Student] SET AUTO_UPDATE_STATISTICS ON GO ALTER DATABASE [Student] SET CURSOR_CLOSE_ON_COMMIT OFF GO ALTER DATABASE [Student] SET CURSOR_DEFAULT GLOBAL GO ALTER DATABASE [Student] SET CONCAT_NULL_YIELDS_NULL OFF GO ALTER DATABASE [Student] SET NUMERIC_ROUNDABORT OFF GO ALTER DATABASE [Student] SET QUOTED_IDENTIFIER OFF GO ALTER DATABASE [Student] SET RECURSIVE_TRIGGERS OFF GO ALTER DATABASE [Student] SET DISABLE_BROKER GO ALTER DATABASE [Student] SET AUTO_UPDATE_STATISTICS_ASYNC OFF GO ALTER DATABASE [Student] SET DATE_CORRELATION_OPTIMIZATION OFF GO ALTER DATABASE [Student] SET TRUSTWORTHY OFF GO ALTER DATABASE [Student] SET ALLOW_SNAPSHOT_ISOLATION OFF GO ALTER DATABASE [Student] SET PARAMETERIZATION SIMPLE GO ALTER DATABASE [Student] SET READ_COMMITTED_SNAPSHOT OFF GO ALTER DATABASE [Student] SET HONOR_BROKER_PRIORITY OFF GO ALTER DATABASE [Student] SET READ_WRITE GO ALTER DATABASE [Student] SET RECOVERY FULL GO ALTER DATABASE [Student] SET MULTI_USER GO ALTER DATABASE [Student] SET PAGE_VERIFY CHECKSUM GO ALTER DATABASE [Student] SET DB_CHAINING OFF GO EXEC sys.sp_db_vardecimal_storage_format N'Student', N'ON' GO USE [Student] GO /****** Object: Table [dbo].[User] Script Date: 05/20/2016 11:36:27 ******/ SET ANSI_NULLS ON GO SET QUOTED_IDENTIFIER ON GO CREATE 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,如下圖:
三、添加增刪改查頁面。
1,增加add.aspx

2、修改edit.aspx
3、列表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>"); } } } } } }