1.
普通存储过程
如数据库有如下存储过程
create proc sp_singleresultset
as
set nocount on
select * from customers
然后在IDE服务资源管理器中拖入到dbml中,保存,它就会生成
sp_singleresultset的方法,
方法如下:
Code
[Function(Name="dbo.sp_singleresultset")]
public ISingleResult<sp_singleresultsetResult> sp_singleresultset()
{
IExecuteResult result = this.ExecuteMethodCall(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())));
return ((ISingleResult<sp_singleresultsetResult>)(result.ReturnValue));
}
他会自动返回存储过返回的东西。
Linq to Object 代码
var 单结果集存储过程 =
from c in ctx.sp_singleresultset()
select c;
这样就得到了存储过程返回的结果集了
2.带参数的存储过程
创建如下存储过程:
create proc [dbo].[sp_withparameter]
@customerid nchar(5),
@rowcount int output
as
set nocount on
set @rowcount = (select count(*) from customers where customerid = @customerid)
执行
Code
int? rowcount = -1;
ctx.sp_withparameter("", ref rowcount);
Response.Write(rowcount);
ctx.sp_withparameter("ALFKI", ref rowcount);
Response.Write(rowcount);
3.多结果集的存储过程
创建一个多结果集的存储过程
create proc [dbo].[sp_multiresultset]
as
set nocount on
select * from customers
select * from employees
找到生成的存储过程方法:
Code
[Function(Name="dbo.sp_multiresultset")]
public ISingleResult<sp_multiresultsetResult> sp_multiresultset()
{
IExecuteResult result = this.ExecuteMethodCall(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())));
return ((ISingleResult<sp_multiresultsetResult>)(result.ReturnValue));
} 修改为:
Code
[Function(Name="dbo.sp_multiresultset")]
[ResultType(typeof(Customer))]
[ResultType(typeof(Employee))]
public IMultipleResults sp_multiresultset()
{
IExecuteResult result = this.ExecuteMethodCall(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())));
return (IMultipleResults)(result.ReturnValue);
} 代码测试:
Code
var 多结果集存储过程 = ctx.sp_multiresultset();
var Customers = 多结果集存储过程.GetResult<Customer>();
var Employees = 多结果集存储过程.GetResult<Employee>();
GridView1.DataSource = from emp in Employees where emp.FirstName.Contains("A") select emp;
GridView1.DataBind();
GridView2.DataSource = from c in Customers where c.CustomerID.StartsWith("A") select c;
GridView2.DataBind();