ef 增删改教程

 

        好了,废话不说了,能看到这篇文章的,应该都是想知道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,如下图:
 

选择空模板
 
二、添加EF的ADO.NET实体数据模型,如下图:

 
命名为:Student
 


 
点击:新建连接
 

 
填写本地SQL数据库的链接,然后选择:Student数据库,如下:
 
 
点击“确定”
 
 
点击:“下一步”
 
选择“6.x”,这里,如果你们用的是VS2013,选“5.0”也一样。
 
 
然后点击“完成”。如下图:
 
添加实体类数据模型到此结束。
 
三、添加增删改查页面。
      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>");
                    }
                }
            }
        }
    }
}  
 
复制代码
posted @ 2020-06-11 16:05  厦门哈韩  阅读(359)  评论(0编辑  收藏  举报