我正在使用Asp.net核心和EF核心进行应用程序开发。基本上,我想从单个存储过程中获取多个结果集。过去两天一直在搜索,但没有找到相关内容。尝试找出解决方案来解决这个问题。
这是我的存储过程:
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
ALTER PROCEDURE [dbo].[usp_CustomerAll_sel]
@SomeOutput int OUT
AS
BEGIN
SET NOCOUNT ON;
SELECT *
FROM [dbo].[Customer]
SELECT @SomeOutput = @@rowcount + 25 --This number 25 is a variable from a complex query but always an integer
END
我在那张表里有两条记录,因此基本上它应该返回一个客户类型的表格,输出参数应该返回27。
现在从我的 .net 代码中,我到目前为止尝试过的是:
[HttpGet]
public async Task<Tuple<IEnumerable<Customer>, int>> GetAllCustomer()
{
var votesParam = new SqlParameter
{
ParameterName = "SomeOutput",
Value = -1,
Direction = ParameterDirection.Output
};
var y = await _customerContext.Customers.FromSql("usp_CustomerAll_sel @SomeOutput out", votesParam).ToArrayAsync();
return new Tuple<IEnumerable<Customer>, int>(y, (int)votesParam.Value);
}
上面的代码返回了一个列表,但我没有从数据库中获取到输出参数的值。(int)votesParam.Value
显示为 null。
现在如果我使用 ExecuteNonQueryAsync
,那么我可以获取到输出参数,但是没有实际的数据。
private async Task ExecuteStoredProc()
{
DbCommand cmd = _customerContext.Database.GetDbConnection().CreateCommand();
cmd.CommandText = "dbo.usp_CustomerAll_sel";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("@SomeOutput", SqlDbType.BigInt) { Direction = ParameterDirection.Output, Value = -1 });
if (cmd.Connection.State != ConnectionState.Open)
{
cmd.Connection.Open();
}
await cmd.ExecuteNonQueryAsync();
long SomeOutput = (long)cmd.Parameters["@SomeOutput"].Value;
}
有没有办法同时获取结果集和输出参数,并将它们作为元组返回?
当我只输入硬编码的值时,它看起来像:
[HttpGet]
public async Task<Tuple<IEnumerable<Customer>, int>> GetAllCustomer()
{
var votesParam = new SqlParameter
{
ParameterName = "SomeOutput",
Value = -1,
Direction = ParameterDirection.Output
};
var y = await _customerContext.Customers.FromSql("usp_CustomerAll_sel @SomeOutput out", votesParam).ToArrayAsync();
return new Tuple<IEnumerable<Customer>, int>(y, **25**);
}
而结果如下:
{"item1":[{"customerId":1,"customerName":"Cus1"},{"customerId":2,"customerName":"Cus2"}],"item2":27}
基本上这就是我在寻找的内容...需要帮忙吗?