SQL 服务器 - C# - 将参数传递给存储过程并返回 IEnumerable

本文关键字:存储过程 返回 IEnumerable 参数传递 服务器 SQL | 更新日期: 2023-09-27 17:56:46

可以直接在查询中传递参数吗,如下所示?

有错误,所以有人可以帮忙吗?

public IEnumerable ListTop10countries(string direction)
{
    using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MYCON"].ToString()))
    {
        var list = con.Query<OutputCountries>("Usp_GetTop10", direction).AsEnumerable();       
        return list;
    }
}

错误:

An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll but was not handled in user code
Additional information: Procedure or function 'Usp_GetTop10' expects parameter '@direction', which was not supplied.

存储的 proc 脚本如下所示:

CREATE proc [dbo].[Usp_GetTop10]
@direction nvarchar(30)
as
begin
SELECT TOP 10 
      [country]    
      ,[Tons]
  FROM [master].[dbo].[a]
  where direction = @direction
  order by [Tons] Desc
end
GO

SQL 服务器 - C# - 将参数传递给存储过程并返回 IEnumerable

试试这个

public IEnumerable ListTop10countries(string mydirection)
{
    using (SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MYCON"].ToString()))
    {
         var list = con.Query<OutputCountries>("Usp_GetTop10", new {direction = mydirection}, commandType: CommandType.StoredProcedure).AsEnumerable();
         return list;
    }
}