LINQ to SQL语句(20)之存储过程2010-12-11 博客园 李永京存储过程在我们编写程序中,往往需要一些存储过程,在LINQ to SQL中 怎么使用呢?也许比原来的更简单些。下面我们以NORTHWND.MDF数据库中自带的 几个存储过程来理解一下。1.标量返回在数据库中,有名为 Customers Count By Region的存储过程。该存储过程返回顾客所在 "WA"区域的数量。ALTER PROCEDURE [dbo]. [NonRowset] (@param1 NVARCHAR(15)) AS BEGIN SET NOCOUNT ON; DECLARE @count int SELECT @count = COUNT(*)FROM Customers WHERECustomers.Region = @Param1 RETURN @count END我们只要把这个存储过程拖到O/R设 计器内,它自动生成了以下代码段:[Function(Name = "dbo.[Customers Count By Region]")] public int Customers_Count_By_Region([Parameter (DbType = "NVarChar (15)")] string param1) { IExecuteResult result = this.ExecuteMethodCall(this, ((MethodInfo) (MethodInfo.GetCurrentMethod())), param1); return ((int) (result.ReturnValue)); }我们需要时,直接调用就可以了, 例如:int count = db.CustomersCountByRegion ("WA"); Console.WriteLine(count);语句描述:这 个实例使用存储过程返回在“WA”地区的客户数。2.单一结 果集从数据库中返回行集合,并包含用于筛选结果的输入参数。 当我们执行 返回行集合的存储过程时,会用到结果类,它存储从存储过程中返回的结果。下面的示例表示一个存储过程,该存储过程返回客户行并使用输入参数 来仅返回将“London”列为客户城市的那些行的固定几列。 ALTER PROCEDURE [dbo].[Customers By City] -- Add the parameters for the stored procedure here (@param1 NVARCHAR(20)) AS BEGIN -- SET NOCOUNT ON added to prevent extra result sets from -- interfering with SELECT statements. SET NOCOUNT ON; SELECT CustomerID, ContactName, CompanyName, City from Customers as c where c.City=@param1 END拖到O/R设计器内,它自动生成了以下代码 段:[Function(Name="dbo.[Customers By City]")] public ISingleResult<Customers_By_CityResult> Customers_By_City( [Parameter(DbType="NVarChar(20)")] string param1) { IExecuteResult result = this.ExecuteMethodCall(this, ( (MethodInfo) (MethodInfo.GetCurrentMethod())), param1); return ((ISingleResult<Customers_By_CityResult>) (result.ReturnValue)); }我们用下面的代码调用:ISingleResult<Customers_By_CityResult> result = db.Customers_By_City("London"); foreach (Customers_By_CityResult cust in result) { Console.WriteLine("CustID={0}; City={1}", cust.CustomerID, cust.City); }语句描述:这 个实例使用存储过程返回在伦敦的客户的 CustomerID和City。