通过SqlMapper调用存储过程时发送参数.c#中的查询

本文关键字:参数 查询 SqlMapper 调用 存储过程 通过 | 更新日期: 2023-09-27 18:11:40

我有以下SP呼叫

        public IEnumerable<classfile> GetData(bool isactive)
        {
            using (SqlConnection cnn = this.OpenConnection())
            {
                 IList<classfile> SampleList = SqlMapper.Query<classfile>(cnn, "SPName").ToList();
                cnn.Close();
                return SampleList.ToList();
            }
        }

如何将参数与上述dapper SP调用一起发送

I tried following

        public IEnumerable<classfile> GetData(bool isactive)
        {
            using (SqlConnection cnn = this.OpenConnection())
            {
                 var parameters = new DynamicParameters();
                 parameters.Add("@isActive", isactive);
                 IList<classfile> SampleList = SqlMapper.Query<classfile>(cnn, "SPName", parameters).ToList();
                cnn.Close();
                return SampleList.ToList();
            }
        }

但是它的运行时得到如下错误

过程或函数'SPName'期望参数'@isActive',其中未提供。

通过SqlMapper调用存储过程时发送参数.c#中的查询

自己找到答案

    public IEnumerable<classfile> GetData(bool isactive)
    {
        using (SqlConnection cnn = this.OpenConnection())
        {
             DynamicParameters parameters = new DynamicParameters();
             parameters.Add("@isActive", isactive);
             IList<classfile> SampleList = SqlMapper.Query<classfile>(cnn, "SPName", parameters, commandType: CommandType.StoredProcedure).ToList();
            cnn.Close();
            return SampleList.ToList();
        }
    }

或者你可以这样写

            IList<classfile> SampleList = SqlMapper.Query<classfile>(cnn, "SPName", new
            {
                isActive = isactive
            }
            , commandType: CommandType.StoredProcedure).ToList();