本人新手,在csdn根据许多博主的文章进行学习,终于努力得到了回报,想把这次的经验共享给大家文件我也会上传到资源里供大家参考!不喜勿喷,有什么建议可以评论,我一定会加以学习,废话不多说,开始我的表演!
一、新建数据库了
创建数据库Test
然后对这个Test文件新建查询
代码如下:
use Test
CREATE TABLE [dbo].[User](
[Id] [int] IDENTITY(1,1) NOT NULL,
[UserName] [nvarchar](32) NULL,
[Age] [int] NULL,
[Address] [nvarchar](64) 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]
二、接下来新建一个asp.net的web站点
使用空模版
三、使用EF的ADO.NET实体数据模型
ctrl+shift+a(新建项目)
点击来自数据库的EF设计器
点击新建连接
首先选择你的数据库,登录服务器可以选择(我用的是用户名登录,可以选择你的验证方式),随后选择你的数据库进行测试连接!
四、创建ASPX页面
简单的说一下我们网页的构成
1.Add.aspx(增加用户):增
2.List.aspx(查看用户与删除用户):查删
3.Edit.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>
</head>
<body>
<form id="form1" runat="server">
<table class="tab">
<tr class="tr">
<td class="td">姓名</td>
<td class="td">
<asp:TextBox id="tb1" runat="server" />
</td>
</tr>
<tr class="tr">
<td class="td">年龄</td>
<td class="td">
<asp:TextBox id="tb2" runat="server" />
</td>
</tr>
<tr class="tr">
<td class="td">性别</td>
<td class="td">
<asp:TextBox id="tb3" runat="server" />
</td>
</tr>
<tr class="tr">
<td class="td">
<a href="list.aspx" runat="server">返回列表</a>
</td>
<td class="td">
<asp:Button ID="Btn2" Text="确认提交" OnClick="Btn2_Click" runat="server" />
</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;
using SJtest;
namespace LMX.EF.Web
{
public partial class add : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Btn2_Click(object sender, EventArgs e)
{
User info = new User
{
Age =Convert.ToInt32(this.tb2.Text.Trim()),
Name = this.tb1.Text.Trim(),
Sex = this.tb3.Text.Trim(),
};
bool result = Add(info);
if (result == true)
{
Response.Write("<script>alert('添加成功')</script>");
}
else
{
Response.Write("<script>alert('请重新添加')</script>");
return;
}
}
public bool Add(User info)
{
StudentEntities db = new StudentEntities();
db.User.Add(info);
return db.SaveChanges() > 0;
}
}
}
<%@ 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>
</head>
<body>
<form id="form1" runat="server">
<br />
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False" DataKeyNames="ID" DataSourceID="SqlDataSource1" OnRowCommand="GridView1_RowCommand" >
<Columns>
<asp:BoundField DataField="ID" HeaderText="ID" InsertVisible="False" ReadOnly="True" SortExpression="ID" />
<asp:BoundField DataField="Name" HeaderText="Name" SortExpression="Name" />
<asp:BoundField DataField="Age" HeaderText="Age" SortExpression="Age" />
<asp:BoundField DataField="Sex" HeaderText="Sex" SortExpression="Sex" />
<asp:TemplateField HeaderText="操作" >
<ItemTemplate>
<asp:Button runat="server" Id="btnDel" Text="删除" CommandName="Delete" CommandArgument='<%# Eval("ID") %>'/>
<asp:Button runat="server" Id="Button1" Text="编辑" CommandName="Update" CommandArgument='<%# Eval("ID") %>'/>
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:StudentConnectionString %>" DeleteCommand="DELETE FROM [User] WHERE [ID] = @ID" InsertCommand="INSERT INTO [User] ([Name], [Age], [Sex]) VALUES (@Name, @Age, @Sex)" SelectCommand="SELECT [ID], [Name], [Age], [Sex] FROM [User]" UpdateCommand="UPDATE [User] SET [Name] = @Name, [Age] = @Age, [Sex] = @Sex WHERE [ID] = @ID">
<DeleteParameters>
<asp:Parameter Name="ID" Type="Int32" />
</DeleteParameters>
<InsertParameters>
<asp:Parameter Name="Name" Type="String" />
<asp:Parameter Name="Age" Type="Int32" />
<asp:Parameter Name="Sex" Type="String" />
</InsertParameters>
<UpdateParameters>
<asp:Parameter Name="Name" Type="String" />
<asp:Parameter Name="Age" Type="Int32" />
<asp:Parameter Name="Sex" Type="String" />
<asp:Parameter Name="ID" Type="Int32" />
</UpdateParameters>
</asp:SqlDataSource>
<a runat="server" href="add.aspx">继续添加
</a><br />
</form>
</body>
</html>
list.aspx后端
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SJtest;
namespace LMX.EF.Web
{
public partial class list : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
}
}
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
var handleName = e.CommandName;
var value = e.CommandArgument as string;
if (handleName=="Delete")
{
string strID = value;
int iID = int.Parse(strID);
using (StudentEntities ent = new StudentEntities())
{
var user = ent.User.FirstOrDefault(s => s.ID == iID);
User aUser = (from c in ent.User where c.ID == iID select c).FirstOrDefault();
// if (user != null)
// {
ent.User.Remove(user);
// ent.User.Remove(aUser);
if (ent.SaveChanges() > 0)
{
Response.Write("删除成功。");
}
else
{
Response.Write("删除失败。");
}
}
}
else
{
Response.Redirect("edit.aspx?id="+value);
}
}
}
}
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>
<style type="text/css">
.auto-style1 {
width: 150px;
}
</style>
</head>
<body>
<form id="form1" runat="server">
<table class="tab">
<tr class="tr">
<td class="td">用户ID</td>
<td class="auto-style1">
<asp:TextBox ID="id" runat="server" ReadOnly="true"></asp:TextBox>
</td>
</tr>
<tr class="tr">
<td class="td">姓名</td>
<td class="auto-style1">
<asp:TextBox ID="Name" runat="server"></asp:TextBox>
</td>
</tr>
<tr class="tr">
<td class="td">年龄</td>
<td class="auto-style1">
<asp:TextBox ID="Age" runat="server"></asp:TextBox>
</td>
</tr>
<tr class="tr">
<td class="td">性别</td>
<td class="auto-style1">
<asp:TextBox ID="Sex" runat="server"></asp:TextBox>
</td>
</tr>
<tr class="tr">
<td class="td">
<a href="list.aspx">返回列表</a>
</td>
<td class="auto-style1">
<asp:Button ID="btnSubmit" runat="server" Text="确认更新" OnClick="btnSubmit_Click" />
</td>
</tr>
</table>
</form>
</body>
</html>
edit.aspx后端
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SJtest;
namespace LMX.EF.Web
{
public partial class edit : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string message = Request.QueryString["id"];
if (!string.IsNullOrEmpty(message))
{
var iID = Convert.ToInt32(message);
using (StudentEntities ent = new StudentEntities())
{
var user = ent.User.FirstOrDefault(s => s.ID == iID);
Age.Text = user.Age.ToString();
Name.Text = user.Name;
Sex.Text = user.Sex;
}
}
}
}
/// <summary>
/// 提交修改
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
///
protected void btnSubmit_Click(object sender, EventArgs e)
{
string message = Request.QueryString["id"];
if (string.IsNullOrEmpty(message))
{
User info = new User
{
Age = Convert.ToInt32(this.Age.Text.Trim()),
Name = this.Name.Text.Trim(),
Sex = this.Sex.Text.Trim(),
};
bool vlaue = Add(info);
if (vlaue == true)
{
Response.Write("<script>alert('添加成功')</script>");
}
else
{
Response.Write("<script>alert('请重新添加')</script>");
return;
}
}
else
{ string strID = message;
int iID = int.Parse(strID);
using (StudentEntities ent = new StudentEntities())
{
var user = ent.User.FirstOrDefault(s => s.ID == iID);
user.Age = Convert.ToInt32(Age.Text);
user.Name = Name.Text;
user.Sex = Sex.Text;
ent.SaveChanges();
}
}
}
public bool Add(User info)
{
StudentEntities db = new StudentEntities();
db.User.Add(info);
return db.SaveChanges() > 0;
}
protected void SqlDataSource1_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
{
}
}
}
写到这里就完成啦,大家可以自行试验,如果有需要的可以下载我的资源进行学习!!!
(转载请标注作者地址和姓名)