调用存储过程从EntityFramework
Prerequisites
The prerequisite for running these examples are the following sample tables with test data and a Stored Procedure. The following script help to generate the table with test data and a Stored Procedure.
--First we create Department Master and Employee Master tables.
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[DepartmentMaster]') AND type in (N'U'))
DROP TABLE [dbo].[DepartmentMaster]
GO
CREATE TABLE [dbo].[DepartmentMaster](
[DepartmentId] [int] IDENTITY(1,1) NOT NULL,
[DepartmentName] [varchar](50) NULL,
[Status] [tinyint] NULL,
CONSTRAINT [PK_DepartmentMaster] PRIMARY KEY CLUSTERED
(
[DepartmentId] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF,ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[EmployeeMaster]') AND type in(N'U'))
DROP TABLE [dbo].[EmployeeMaster]
GO
CREATE TABLE [dbo].[EmployeeMaster](
[EmployeeID] [int] IDENTITY(1,1) NOT NULL,
[EmployeeName] [varchar](100) NULL,
[DepartmentID] [int] NULL,
[Status] [tinyint] NULL,
CONSTRAINT [PK_EmployeeMaster] PRIMARY KEY CLUSTERED
(
[EmployeeID] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS =ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]
--Stored Procedure that return Employee Details i.e Employee ID, Employee Name and Department Name
IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[GetEmployeeData]') AND type in(N'P', N'PC'))
DROP PROCEDURE [dbo].[GetEmployeeData]
GO
CREATE PROCEDURE [dbo].[GetEmployeeData]
AS
BEGIN
SELECT EmployeeID,EmployeeName,DepartmentName FROM EmployeeMaster E
INNER JOIN DepartmentMaster D ON E.DepartmentID = D.DepartmentId
END
--Inserting some Dummy Data.
SET IDENTITY_INSERT [dbo].[DepartmentMaster] ON
INSERT [dbo].[DepartmentMaster] ([DepartmentId], [DepartmentName], [Status]) VALUES (1, N'Maths', 0)
INSERT [dbo].[DepartmentMaster] ([DepartmentId], [DepartmentName], [Status]) VALUES (2, N'English', 0)
INSERT [dbo].[DepartmentMaster] ([DepartmentId], [DepartmentName], [Status]) VALUES (3, N'Physics', 0)
SET IDENTITY_INSERT [dbo].[DepartmentMaster] OFF
SET IDENTITY_INSERT [dbo].[EmployeeMaster] ON
INSERT [dbo].[EmployeeMaster] ([EmployeeID], [EmployeeName], [DepartmentID], [Status]) VALUES (1, N'Tejas',1, 0)
INSERT [dbo].[EmployeeMaster] ([EmployeeID], [EmployeeName], [DepartmentID], [Status]) VALUES (2,N'Rakesh', 1, 0)
INSERT [dbo].[EmployeeMaster] ([EmployeeID], [EmployeeName], [DepartmentID], [Status]) VALUES (3,N'Jignesh', 2, 0)
INSERT [dbo].[EmployeeMaster] ([EmployeeID], [EmployeeName], [DepartmentID], [Status]) VALUES (4, N'Kunal',3, 0)
SET IDENTITY_INSERT [dbo].[EmployeeMaster] OFF
1. Stored Procedure as Entity Function
The Entity Framework has the capability of importing a Stored Procedure as a function. We can also map the result of the function back to any entity type or complex type.
The following is the procedure to import and use a Stored Procedure in Entity Framework.
Step 1: Import Stored Procedure
When we finish this process, the selected Stored Procedure is added to the model browser under the Stored Procedure Node.
Step 2: Right-click Stored Procedure and select "Add Function Import".
Step 3: Here, we can map a returned object of our Stored Procedure. The return type may be a scalar value or a collection of Model Entities or a collection of Complex (Custom) Entity. From this screen we can create a Complex Entity as well.
Now, we can call the Stored Procedure as an entity function using the following code. The entity function returns a complex type called "EmployeeDetails".
using (Entities context = new Entities())
{
IEnumerable<EmployeeDetails> empDetails = context.GetEmployeeData();
}
2. Call Stored Procedure using ExecuteStoreQuery<T> function
"ExecuteStoreQuery<T>" should be used to query data. This method only works if T has a Default Constructor and also a Property name is the same as the returned column names. "T" can be any generic class or any data type and it might not be a part of an EF generated entity.
The following is the procedure to retrieve data using the "ExecuteStoreQuery<T>" method from a Stored Procedure.
Step 1:
The method "T" can be anything, it may be an EF Generated entity or it may be a Custom Entity, so first I am creating a Custom Entity "EmployeeDetail". Here the EmployeeDetail properties name must be the same as the returned column of the select statement of the Stored Procedure.
// Creating Custom class to hold result of Stored Procedure
public class EmployeeDetail
{
public int EmployeeID { get; set; }
public string EmployeeName { get; set; }
public string DepartmentName { get; set; }
}
// using Object Context (EF4.0)
using (Entities context = new Entities())
{
IEnumerable<EmployeeDetails> empDetails = context.ExecuteStoreQuery<EmployeeDetails>
("exec GetEmployeeData").ToList();
}
// using DBContext (EF 4.1 and above)
using (Entities context = new Entities())
{
IEnumerable<EmployeeDetails> empDetails = context. Database.SqlQuery
< EmployeeDetails >("exec GetEmployeeData ", null).ToList();
}
3. Call Stored Procedure using DbDataReader
We can also retrieve data or call a Stored Procedure using a SQL Connection Command and DbDataReader. The Object Context has a translate method that translates the entity data from DbDataReader into the requested type object. This method enables us to execute a standard ADO.Net query against a data source and return data rows into entity objects. Using the following code we can call a Stored Procedure and retrieve data in entity form.
using (Entities context = new Entities())
{
string ConnectionString = (context.Connection as EntityConnection).StoreConnection.ConnectionString;
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(ConnectionString);
builder.ConnectTimeout = 2500;
SqlConnection con = new SqlConnection(builder.ConnectionString);
System.Data.Common.DbDataReader sqlReader;
con.Open();
using (SqlCommand cmd = con.CreateCommand())
{
cmd.CommandText = "GetEmployeeData";
cmd.CommandType = System.Data.CommandType.StoredProcedure;
cmd.CommandTimeout = 0;
sqlReader = (System.Data.Common.DbDataReader)cmd.ExecuteReader();
IEnumerable<EmployeeDetail> empDetails = context.Translate<EmployeeDetail>(sqlReader).ToList();
}
}
Conclusion
Using the methods described above, we can call a Stored Procedure and retrieve data as a scalar or complex value.
调用存储过程从EntityFramework的更多相关文章
- 使用EntityFramework调用存储过程并获取存储过程返回的结果集
[实习]刚入职,公司要求完成两个任务,任务要求使用存储过程和事务,其中一个问题要获取存储过程的查询结果集.经过多方查找和自己的实践,终于找到了方法.这里记录一下. 看到的这篇文章中给出的例子是查询单个 ...
- spring data jpa 调用存储过程
网上这方面的例子不是很多,研究了一下,列出几个调用的方法. 假如我们有一个mysql的存储过程 CREATE DEFINER=`root`@`localhost` PROCEDURE `plus1in ...
- myabatis oracle 调用存储过程返回list结果集
Mapper.xml 配置 <resultMap type="emp" id="empMap"> <id property="emp ...
- IBatis.Net使用总结(四)-- IBatis 调用存储过程
IBatis 调用存储过程 http://www.cnblogs.com/jeffwongishandsome/archive/2010/01/10/1543219.html http://www.c ...
- SQL SERVER使用ODBC 驱动建立的链接服务器调用存储过程时参数不能为NULL值
我们知道SQL SERVER建立链接服务器(Linked Server)可以选择的驱动程序非常多,最近发现使用ODBC 的 Microsoft OLE DB 驱动程序建立的链接服务器(Linked S ...
- 【Java EE 学习 29 下】【JDBC编程中操作Oracle数据库】【调用存储过程的方法】
疑问:怎样判断存储过程执行之后返回值是否为空. 一.连接oracle数据库 1.需要的jar包:在安装的oracle中就有,所以不需要到官网下载,我的oracle11g下:D:\app\kdyzm\p ...
- MyBatis学习总结(六)——调用存储过程(转载)
本文转载自:http://www.cnblogs.com/jpf-java/p/6013518.html 一.提出需求 查询得到男性或女性的数量, 如果传入的是0就女性否则是男性 二.准备数据库表和存 ...
- C# 调用存储过程操作 OUTPUT参数和Return返回值
本文转载:http://www.cnblogs.com/libingql/archive/2010/05/02/1726104.html 存储过程是存放在数据库服务器上的预先编译好的sql语句.使用存 ...
- jdbc调用存储过程和函数
1.调用存储过程 public class CallOracleProc { public static void main(String[] args) throws Exception{ Stri ...
随机推荐
- EF6+MYSQL之初体验
初次使用EF6+MYSQL 这次的项目时间可拉得够长的,定制开发就是这样.客户真正用上了才能基本上不再改了.起先项目是php实现的,改造成桌面程序.用.net winform开发,像这种小项目肯定要用 ...
- JavaScript基础知识整理
只整理基础知识中关键技术,旨在系统性的学习和备忘. 1.在 JScript 中 null 和 undefined 的主要区别是 null 的操作象数字 0,而 undefined 的操作象特殊值NaN ...
- 基于jQuery点击加载动画按钮特效
分享一款基于jQuery点击加载动画按钮特效.这是一款基于jQuery+CSS3实现的鼠标点击按钮加载动画特效代码.效果图如下: 在线预览 源码下载 实现的代码. html代码: <div ...
- 自动化回归测试案例评价标准 MeRest
自动化回归测试案例评价标准试图定义不同维度来评价自动化案例的优劣,作为后续我们评判讨论测试框架.测试技术和测试案例编写模式的基础.那什么是好的自动化回归测试案例呢?简而言之,就是投资回报率高的案例,因 ...
- 企业云部署要如何选择IaaS PaaS和SaaS
1为什么IaaS成了灵丹妙药 我非常惊讶,为什么很多传统企业已经接受了云计算,但接受的方式却往往不尽人意.对大多数企业来说,云计算的投入产出比相对较小,并且局限于基础设施层的环节. 就目前而言,大 ...
- nginx 更新提示端口占用的解决办法
最近更新ubuntu下的nginx,报了以下的错误, [emerg]: bind() to 0.0.0.0:80 failed (98: Address already in use) 可以看到,80 ...
- sql server service broker中调用存储过程执行跨库操作,不管怎么设置都一直提示 服务器主体 "sa" 无法在当前安全上下文下访问数据库 "dbname"。
用sql server自带的消息队列service borker,调用存储过程中,执行了一个跨库的操作,先是用了一个用户,权限什么都给够了,但是一直提示 服务器主体 "user" ...
- SQL Server中的事务日志管理(3/9):事务日志,备份与恢复
当一切正常时,没有必要特别留意什么是事务日志,它是如何工作的.你只要确保每个数据库都有正确的备份.当出现问题时,事务日志的理解对于采取修正操作是重要的,尤其在需要紧急恢复数据库到指定点时.这系列文章会 ...
- js 各种数值类型正则匹配检测
随拿随用只js正则表达式,反正平时工作我是不写正则的,大神请自动绕行: 验证数字的正则表达式集验证数字:^[0-9]*$验证n位的数字:^\d{n}$验证至少n位数字:^\d{n,}$验证m-n位的数 ...
- python下的orm基本操作(1)--Mysql下的CRUD简单操作(含源码DEMO)
最近逐渐打算将工作的环境转移到ubuntu下,突然发现对于我来说,这ubuntu对于我这种上上网,收收邮件,写写博客,写写程序的时实在是太合适了,除了刚接触的时候会不怎么完全适应命令行及各种权限管理, ...