使用存储过程的 Entity Framework CRUD 操作






4.81/5 (22投票s)
如何在 Entity Framework 中使用存储过程实现 CRUD 操作。
引言
在本文中,我想分享一些关于 Entity Framework 的内容,即如何在 Entity Framework 中使用存储过程实现 CRUD 操作。
在本说明中,有两种实现 CRUD 操作的方法
- 通过使用
ExecuteStoreCommand
和ExecuteStoreQuery
调用存储过程,而无需映射到模型。 - 通过将存储过程映射到模型。
好的,首先我们将看到如何将存储过程映射到模型以实现 CRUD 操作。
从 VS2010 创建一个空的 Web 应用程序,请参见
首先让我们创建一个示例表。由于我的机器上没有安装 SQL Server,因此我将 SQL Server 数据库添加如下
在这里,您可以根据您的命名约定使用名称 *Database1.mdf*。现在在服务器资源管理器中,您将看到您的数据库,我们将添加一个表和一些存储过程,如下所示
添加所需的列并使用所需的名称保存表。在开始使用 Entity Framework 之前,最重要的是在您的表中拥有一个主键。
现在我的表如下所示,我们将对其执行 CRUD 操作。
好的,现在让我们创建用于插入、更新、删除和选择操作的存储过程。
插入存储过程
CreatePROCEDURE dbo.InsertEmployee
(
@ID int,
@EmpName varchar(50),
@EmpAddress varchar(50)
)
AS
Begin
insert into Employee(EmpID,Emp_Name,Emp_Address)values(@ID,@EmpName,@EmpAddress)
END
删除存储过程
Create PROCEDURE dbo.deleteEmp
(
@ID int
)
As
Begin
delete from Employee where EmpID=@ID
End
Select
Create PROCEDURE dbo.SelectEmployee
As
Begin
select * from Employee
End
更新
Create PROCEDURE dbo.UpdateEmployee
(@ID int,
@EmpName varchar(50),
@EmpAddress varchar(50))
As
Begin
update Employee set Emp_Name=@EmpName,Emp_Address=@EmpAddress where EmpID=@ID
End
我们已经完成了数据库的操作。现在让我们创建一个示例页面并将一个实体模型添加到我们的应用程序。
将实体模型添加到您的应用程序
添加模型后,您将立即拥有此实体数据模型向导,您必须从中选择“从数据库生成”并单击“下一步”
从“选择您的数据”中选择“新建连接”
在此处的“数据源”中,您将通过单击“更改”看到各种数据源,由于我在我的应用程序中创建了我的数据库,我将使用 Microsoft SQL Server 数据库文件 (SqlClient),如果有人使用 SQL Server,您可以从可用选项将其更改为 SQL Server。
由于我正在使用 Microsoft SQL Server 数据库文件 (SqlClient),我将浏览我的数据库文件并单击“确定”。
在这里您将看到我的数据库文件,并且连接设置也将以名称 EntitySampleEntities 保存在 *Web.Config* 中。单击“下一步”,您将在其中找到您创建的所有表和存储过程。选择所需的那个。由于我只创建了一个表和 4 个存储过程,我将选择它们。
初始窗口
完成后,单击“完成”,然后您将看到包含您添加的表的模型,如果存在任何关系,它也会映射它们。到目前为止,我只创建了一个表,它将显示如下
现在我们已经完成了创建数据库并将其添加到实体模型。现在我们将看到如何在不将存储过程映射到模型的情况下执行 CRUD 操作。
我还包括了一些需要的 LINQ 查询,例如自动生成员工 ID 和绑定下拉列表。
创建一个网页并将以下设计添加到该页面
<%@ Page Language="C#" AutoEventWireup="true"
CodeBehind="crud.aspx.cs" Inherits="CRUDentity.crud" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
<title></title>
</head>
<body>
<form id="form1" runat="server">
<div>
<center>
<h3>
Display data in gridview using Entity Framework with out Mapping Stored Procedure
to Model
</h3>
<div style="width: 800px; margin: 0 auto; float: left;">
<asp:GridView ID="grdEmployess" runat="server" BackColor="White" BorderColor="#999999"
DataKeyNames="EmpID" BorderStyle="None" BorderWidth="1px" CellPadding="3"GridLines="Vertical">
<AlternatingRowStyle BackColor="#DCDCDC" />
<EmptyDataTemplate>
No record to show
</EmptyDataTemplate>
<FooterStyle BackColor="#CCCCCC" ForeColor="Black" />
<HeaderStyle BackColor="#000084" Font-Bold="True" ForeColor="White" />
<PagerStyle BackColor="#999999" ForeColor="Black" HorizontalAlign="Center" />
<RowStyle BackColor="#EEEEEE" ForeColor="Black" />
<SelectedRowStyle BackColor="#008A8C" Font-Bold="True" ForeColor="White" />
<SortedAscendingCellStyle BackColor="#F1F1F1" />
<SortedAscendingHeaderStyle BackColor="#0000A9" />
<SortedDescendingCellStyle BackColor="#CAC9C9" />
<SortedDescendingHeaderStyle BackColor="#000065" />
</asp:GridView>
</div>
<br />
<div style="width: 800px; margin: 0 auto; float: left;">
<h3>
Insert Data to table using Entity Framework with out Mapping Stored Procedures to
Model</h3>
<table>
<tr>
<td>
Employee ID :
</td>
<td>
<asp:TextBox ID="txtEmpID" ReadOnly="true" runat="server"></asp:TextBox>
</td>
</tr>
<tr>
<td>
Employee Name :
</td>
<td>
<asp:TextBox ID="txtEmployeeName" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="rqrdEmployeeName" runat="server" ErrorMessage="*"
ControlToValidate="txtEmployeeName" ToolTip="Employee name required"ValidationGroup="g"
Display="Dynamic" ForeColor="Red"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td>
Employee Address :
</td>
<td>
<asp:TextBox ID="txtAddress" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="rqrdAddress" runat="server"
ErrorMessage="*"ControlToValidate="txtAddress"
ToolTip="Address required" ValidationGroup="g"
Display="Dynamic" ForeColor="Red"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td>
</td>
</tr>
<tr align="center">
<td colspan="3">
<asp:Button ID="btnInsert" runat="server" Text="Insert"
ValidationGroup="g"OnClick="btnInsert_Click" />
</td>
</tr>
</table>
</div>
<br />
<div style="width: 800px; margin: 0 auto; float: left;">
<h3>
Edit and Update data using storedprocedure With out mapping it to Model</h3>
<table>
<tr>
<td>
Select Employee ID :
</td>
<td>
<asp:DropDownList ID="ddleditEmpID" runat="server"
AutoPostBack="true"
OnSelectedIndexChanged="ddleditEmpID_SelectedIndexChanged">
</asp:DropDownList>
</td>
</tr>
<tr>
<td>
Employee Name :
</td>
<td>
<asp:TextBox ID="txtedtEmployeeName" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="rqrdedtEmpName" runat="server"
ErrorMessage="*"ControlToValidate="txtedtEmployeeName"
ToolTip="Employee name required" ValidationGroup="g1"
Display="Dynamic"ForeColor="Red"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td>
Employee Address :
</td>
<td>
<asp:TextBox ID="txtedtEmpAddress" runat="server"></asp:TextBox>
<asp:RequiredFieldValidator ID="rqrdedtEmpAddress" runat="server" ErrorMessage="*"
ControlToValidate="txtedtEmpAddress" ToolTip="Address required" ValidationGroup="g1"
Display="Dynamic" ForeColor="Red"></asp:RequiredFieldValidator>
</td>
</tr>
<tr>
<td>
</td>
</tr>
<tr align="center">
<td colspan="4">
<asp:Button ID="btnUpdate" runat="server" Text="Update" OnClick="btnUpdate_Click" />
</td>
</tr>
</table>
</div>
<br />
<div style="width: 800px; margin: 0 auto; float: left;">
<h3>
Delete data using storedprocedure With out mapping it to Model</h3>
<table>
<tr>
<td>
Select Employee ID to Delete :
</td>
<td>
<asp:DropDownList ID="ddlEmpID" runat="server">
</asp:DropDownList>
</td>
</tr>
<tr>
<td>
</td>
</tr>
<tr align="center">
<td colspan="2">
<asp:Button ID="btnDelete" runat="server"
ValidationGroup="g1" Text="Delete"OnClick="btnDelete_Click" />
</td>
</tr>
</table>
</div>
</center>
</div>
</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 System.Data.SqlClient;
namespace CRUDentity
{
public partial class crud : System.Web.UI.Page
{
EntitySampleEntities entities = new EntitySampleEntities();
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
checkMax();
loadGrid();
bindDDL();
}
}
protected void btnInsert_Click(object sender, EventArgs e)
{
Page.Validate("g");
if (Page.IsValid)
{
var ietsParameterID = new SqlParameter("@ID", System.Data.SqlDbType.Int);
ietsParameterID.Value = Convert.ToInt16(txtEmpID.Text);
var ietsParameterEmpName = new SqlParameter("@EmpName", txtEmployeeName.Text);
var ietsParameterEmpAddress = new SqlParameter("@EmpAddress", txtAddress.Text);
entities.ExecuteStoreCommand("InsertEmployee @ID,@EmpName,@EmpAddress",
ietsParameterID, ietsParameterEmpName, ietsParameterEmpAddress);
loadGrid();
checkMax();
bindDDL();
txtAddress.Text = string.Empty;
txtEmployeeName.Text = string.Empty;
}
}
public void checkMax()
{
int? maxEmpID = entities.Employees.Max(q => (int?)q.EmpID);
if (maxEmpID != null)
{
maxEmpID = maxEmpID + 1;
txtEmpID.Text = maxEmpID.ToString();
}
else
{
maxEmpID = 1000;
txtEmpID.Text = maxEmpID.ToString();
}
}
public void loadGrid()
{
var selectData = entities.ExecuteStoreQuery<Employee>("SelectEmployee").ToList();
grdEmployess.DataSource = selectData;
grdEmployess.DataBind();
}
public void bindDDL()
{
var display = from e in entities.Employees select new { e.EmpID };
ddlEmpID.DataSource = display.ToList();
ddlEmpID.DataTextField = "EmpID";
ddlEmpID.DataValueField = "EmpID";
ddlEmpID.DataBind();
ddlEmpID.Items.Insert(0, "--Select--");
ddleditEmpID.DataSource = display.ToList();
ddleditEmpID.DataTextField = "EmpID";
ddleditEmpID.DataValueField = "EmpID";
ddleditEmpID.DataBind();
ddleditEmpID.Items.Insert(0, "--Select--");
}
protected void btnDelete_Click(object sender, EventArgs e)
{
if (ddlEmpID.SelectedItem.Text != "--Select--")
{
var ietsParameterID = new SqlParameter("@ID", ddlEmpID.SelectedItem.Text);
entities.ExecuteStoreCommand("deleteEmp @ID", ietsParameterID);
loadGrid();
checkMax();
bindDDL();
}
}
protected void btnUpdate_Click(object sender, EventArgs e)
{
Page.Validate("g1");
if (Page.IsValid)
{
if (ddleditEmpID.SelectedItem.Text != "--Select--")
{
var ietsParameterID = new SqlParameter("@ID", System.Data.SqlDbType.Int);
ietsParameterID.Value = Convert.ToInt16(ddleditEmpID.SelectedItem.Text);
var ietsParameterEmpName = new SqlParameter("@EmpName", txtedtEmployeeName.Text);
var ietsParameterEmpAddress = new SqlParameter("@EmpAddress", txtedtEmpAddress.Text);
entities.ExecuteStoreCommand("UpdateEmployee @ID,@EmpName,@EmpAddress",
ietsParameterID, ietsParameterEmpName, ietsParameterEmpAddress);
loadGrid();
}
}
}
protected void ddleditEmpID_SelectedIndexChanged(object sender, EventArgs e)
{
if (ddleditEmpID.SelectedItem.Text != "--Select--")
{
int id = Convert.ToInt16(ddleditEmpID.SelectedValue.ToString());
var display = from e1 in entities.Employees
where e1.EmpID.Equals(id)
select new { e1.Emp_Name, e1.Emp_Address };
foreach (var v in display)
{
txtedtEmployeeName.Text = v.Emp_Name;
txtedtEmpAddress.Text = v.Emp_Address;
}
}
}
}
}
首次运行应用程序时
由于表中没有记录,您将看到网格视图为空。您还将看到员工 ID 是只读的,为了避免重复,我将其设为只读,如果您愿意,您可以删除它并执行您需要的操作。
现在我们将看看提交数据后会发生什么
现在我们将编辑记录,请看这里我将更改员工地址,最初是 Hyderabad,我将把它改成其他地址。为此,请选择您需要编辑和更新的员工 ID。由于这里我只有一个员工,我将为他这样做。
编辑员工地址之前
让我们进行删除;为此,我将向表中添加另一个员工,如图所示,然后将其删除。
删除之前
删除之后
就是这样,这就是我们在不将存储过程映射到模型的情况下使用 Entity Framework 执行基本 CRUD 操作的方法。
等待下一个,了解我们如何通过将存储过程映射到模型来使用 Entity Framework 实现 CRUD 操作。