执行存储过程时是否可以从 LINQ To SQL DataContext 取回输出参数?
IEnumerable<Address> result =
ExecuteQuery<Address>(((MethodInfo)(MethodInfo.GetCurrentMethod())),
address, pageIndex, pageSize, totalCount);
其中address
、pageIndex
和pageSize
是输入参数,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;
}
最佳答案
Scott Guthrie 有一个 blog post描述了如何让 LINQ to SQL 与存储过程一起工作。虽然他的帖子没有直接回答您的问题,但它提供了一些可能有用的线索。在 .dbml 类中定义方法时,“LINQ to SQL 将 SPROC 中的‘out’参数映射为引用参数(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属性(property)。它是 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;
关于linq-to-sql - 从 LINQ To SQL ExecuteQuery 中的存储过程捕获输出参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3512941/