从LINQ To SQL ExecuteQuery中的存储过程捕获输出参数

时间:2010-08-18 14:07:56

标签: linq-to-sql stored-procedures output-parameter

执行存储过程时,是否可以从LINQ To SQL DataContext返回输出参数?

IEnumerable<Address> result = 
    ExecuteQuery<Address>(((MethodInfo)(MethodInfo.GetCurrentMethod())), 
       address, pageIndex, pageSize, totalCount);

其中addresspageIndexpageSize是输入参数,TotalCount是输出参数。

如何捕获输出参数?

这是另一种尝试,但又无法获得参数值:


    [Function(Name = "Telecom.AddressSearch")]
        private IEnumerable SearchAddress([Parameter(Name = "address", DbType = "varchar")] string address,
                                             [Parameter(Name = "pageIndex", DbType = "int")] int pageIndex,
                                             [Parameter(Name = "pageSize", DbType = "int")] int pageSize,
                                             [Parameter(Name = "totalCount", DbType = "int")] ref int totalCount)
        {            
            IEnumerable result = ExecuteQuery(((MethodInfo)(MethodInfo.GetCurrentMethod())), address, pageIndex, pageSize, totalCount);

            return result;
        }

1 个答案:

答案 0 :(得分:6)

Scott Guthrie有一个blog post,它描述了如何让LINQ to SQL与存储过程一起工作。虽然他的帖子没有直接回答你的问题,但它提供了可能有用的东西的线索。在.dbml类中定义方法时,“LINQ to SQL将SPROC中的'参数'映射为参数参数(ref关键字)。”您可以尝试使用ref关键字,看看totalCount是否得到更新。

   IEnumerable r = ExecuteQuery(((MethodInfo)(MethodInfo.GetCurrentMethod())),
   address, pageIndex, pageSize, ref totalCount);

<强>更新

我做了更多的研究,并找到了适合你的方法。这来自MSDN article。你需要扩展你的DataContext,但这不应该是一个大问题(看起来你可能已经这样做了)。查看文章了解更多信息,但基本部分是:

[Function(Name="dbo.CustOrderTotal")]
[return: Parameter(DbType="Int")]
public int CustOrderTotal([Parameter(Name="CustomerID", DbType="NChar(5)")] string customerID, [Parameter(Name="TotalSales", DbType="Money")] ref System.Nullable<decimal> totalSales)
{
    IExecuteResult result = this.ExecuteMethodCall(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())), customerID, totalSales);
    totalSales = ((System.Nullable<decimal>)(result.GetParameterValue(1)));
    return ((int)(result.ReturnValue));
}

'this'是你的DataContext。

更新2:

IExecuteResult具有ReturnValue属性。它是Object类型,因此您必须将其强制转换才能获得结果,但它应该允许您获取结果的Enumerable。在你的情况下,这样的事情应该有效:

IExecuteResult result = this.ExecuteMethodCall(this, ((MethodInfo)(MethodInfo.GetCurrentMethod())), address, pageIndex, pageSize, totalCount);
totalCount = ((System.Nullable<decimal>)(result.GetParameterValue(3)));
return (IEnumerable<Address>)result.ReturnValue;