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 = ,
Name = strName,
Sex = strSex
};
ent.User.Add(aNewUser);
if (ent.SaveChanges() > )
{
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() > )
{
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 = ;
aUser.Sex = strSex;
if (ent.SaveChanges() > )
{
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