学习Linq时,经常会遇到Linq存储过程返回问题,这里将介绍Linq存储过程返回问题的解决方法。
存储过程
在我们编写程序中,往往需要一些存储过程,在LINQ to SQL中怎么使用呢?也许比原来的更简单些。下面我们以NORTHWND.MDF数据库中自带的几个存储过程来理解一下。
1.标量返回
在数据库中,有名为Customers Count By Region的存储过程。该Linq存储过程返回顾客所在"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
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
我们只要把这个存储过程拖到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));
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
我们需要时,直接调用就可以了,例如:
int count = db.CustomersCountByRegion("WA");
Console.WriteLine(count);
- 1.
- 2.
语句描述:这个实例使用Linq存储过程返回在“WA”地区的客户数。
2.单一结果集
从数据库中返回行集合,并包含用于筛选结果的输入参数。 当我们执行返回行集合的存储过程时,会用到结果类,它存储从存储过程中返回的结果。
下面的示例表示一个存储过程,该Linq存储过程返回客户行并使用输入参数来仅返回将“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
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
- 10.
- 11.
拖到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));
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
- 8.
- 9.
我们用下面的代码调用:
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);
}
- 1.
- 2.
- 3.
- 4.
- 5.
- 6.
- 7.
语句描述:这个实例使用Linq存储过程返回在伦敦的客户的 CustomerID和City。
【编辑推荐】