是否可以在ExecuteQuery< T>中使用输出参数? [英] Is it possible to use output parameters with ExecuteQuery<T>?
问题描述
通常,当您想直接通过Linq to Sql调用存储过程时,可以使用ExecuteQuery方法:
Normally, when you want to call a stored procedure directly through Linq to Sql, you can use the ExecuteQuery method:
result = dc.ExecuteQuery<MyTable>("Exec myStoredProcedure");
如果需要使用参数调用它,则可以通过字符串替换将其添加:
And if you need to call it with parameters, you can add them through string substitution:
string query = "Exec myStoredProcedure ";
for (int i = 0; i < parameters.Count - 1; i++) {
query += " {" + i + "},";
}
query = query.TrimEnd(',');
result = dc.ExecuteQuery<MyTable>(query, parameters);
但是,如果参数之一是输出变量怎么办?该程序运行后是否可以取回值?
But what if one of the parameters is an output variable? Is it possible to get the value back after the procedure has been run?
推荐答案
Alper Ozcetin's是正确的,您可以在* .dbml中映射StoredProcedures,并且可以将StoredProcedures用作Method.
Alper Ozcetin's is right you can map StoredProcedures in *.dbml and you can use StoredProcedures as Method.
下面是使用AdventureWorks数据库执行此操作的演示,可同时用于vs2008和vs2010
Below is demo doing this with the AdventureWorks DB and works for both vs2008 and vs2010
我通过AdventureWorks创建了以下Proc
Wtih AdventureWorks I created the following Proc
CREATE PROC sp_test (@City Nvarchar(60) , @AddressID int out )
AS
SELECT TOP 10 * FROM Person.Address where City = @City
select top 1 @AddressID = AddressID FROM Person.Address where City = @City
然后我将sp_test添加到dbml并编写了以下程序
I then added sp_test to a dbml and wrote the following program
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Linq;
namespace Test
{
class Program
{
static void Main(string[] args)
{
DataClasses1DataContext dc = new DataClasses1DataContext("SomeSQLConnection);
int? AddressID = null;
ISingleResult<sp_testResult> result = dc.sp_test("Seattle", ref AddressID);
foreach (sp_testResult addr in result)
{
Console.WriteLine("{0} : {1}", addr.AddressID, addr.AddressLine1);
}
Console.WriteLine(AddressID);
}
}
}
这将导致以下输出
23 : 6657 Sand Pointe Lane
91 : 7166 Brock Lane
92 : 7126 Ending Ct.
93 : 4598 Manila Avenue
94 : 5666 Hazelnut Lane
95 : 1220 Bradford Way
96 : 5375 Clearland Circle
97 : 2639 Anchor Court
98 : 502 Alexander Pl.
99 : 5802 Ampersand Drive
13079
您会注意到sp_test方法的输入是ref
You'll notice that the input into the sp_test method is a ref
这篇关于是否可以在ExecuteQuery< T>中使用输出参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!