【问题标题】:C# - Passing parameter to stored procedure and return IEnumerableC# - 将参数传递给存储过程并返回 IEnumerable
【发布时间】:2015-09-02 09:39:27
【问题描述】:

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

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

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

【问题讨论】:

  • 你能把你得到的错误贴出来吗??
  • 我已经添加了错误并更具体地解释了
  • 你在使用 Dapper.net 吗?
  • 是的,我使用 Dapper 作为参考

标签: c# sql-server stored-procedures dapper


【解决方案1】:

试试这个

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;
    }
}

【讨论】:

  • 嗨@sangramparmar 你能解释一下这个答案,并为我把这些点联系起来。我很抱歉问这个问题,但这对我来说有点提前,我试图弄清楚 Query 是否是一种扩展方法以及类型 OutputCountries 我如何创建该类型。提前致谢。
  • 嗨@Nel 你能添加这个吗?我试图实现这一点,但对我来说有点进步。我认为您实施了一种扩展方法,具有一种输出国家/地区。你有更多可以添加的代码吗?谢谢
猜你喜欢
  • 2023-03-14
  • 2015-08-09
  • 2016-04-05
  • 2011-07-22
  • 1970-01-01
相关资源
最近更新 更多