学Linq to sql(五):存储过程2010-11-04 博客园 lovecherry普通存储过程首先在查询分析器运行下面的代码来创建一个存储过程:create proc sp_singleresultsetasset nocount onselect * from customers 然后打开IDE的资源管理器,之前我们从表中拖动表到dbml设计视图,这次我们从存储过程中找到刚才创建的存储过程,然后拖动到设计视图。在方法面板中可以看到已经创建了一个sp_singleresultset的方法,如下图:

然后打开Northwind.designer.cs,可以找到下面的代码:[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));}我们可以发现,IDE为这个存储过程单独生成了返回结果集的实体定义,你可能会觉得很奇怪,IDE怎么知道这个存储过程将会返回哪些数据那?其实,在把存储过程拖拽入dbml设计视图的时候,IDE就执行了类似下面的命令:SET FMTONLY ON;exec Northwind.dbo.sp_singleresultsetSET FMTONLY OFF;这样就可以直接获取存储过程返回的元数据而无须执行存储过程。其实我们存储过程返回的就是顾客表的数据,如果你觉得为存储过程单独设置结果集实体有些浪费的话可以在存储过程的属性窗口中调整返回类型从“自动生成的类型”到Customer,不过以后你只能通过删除方法面板中的存储过程,然后重新添加来还原到“自动生成的类型”。下面,我们可以写如下的Linq to object代码进行查询:var 单结果集存储过程 =from c in ctx.sp_singleresultset()where c.CustomerID.StartsWith("A")select c;