zoukankan      html  css  js  c++  java
  • 使用dapper遇到的问题及解决方法

    在使用dapper进行数据查询时遇到的一个问题,今天进行问题重现做一个记录,免得忘记以后又犯同样的错误。

    自己要实现的是:select * from tablename where id in(1,2)这样的一个查询语句。自己以为的写法应该是这样的,代码如下:

    List<CICUser> userList = new List<CICUser>();
                using (IDbConnection conn = new SqlConnection(sqlConnectionString))
                {
                    int[] idarr = new int[] { 1, 2, 3 };
                    string sqlCommandText = @"SELECT * FROM CICUser s WHERE s.UserId IN (@UserId) ";
                    
                    userList = conn.Query<CICUser>(sqlCommandText, new { UserId = idarr },null,true,null, CommandType.Text).ToList();
                    
    
                }

    运行之后报错,如下:

     找问题原因是就是觉得自己写的没有错,那到底是哪里出了问题呐,又不想去研究源码,那就找看咋个拿到生成的sql语句,比对下sql语句,看哪里有问题。

    接下来就根据数据库的工具,进行跟踪得到sql语句,如下:

    exec sp_executesql N'SELECT * FROM CICUser s WHERE s.UserId IN ((@UserId1,@UserId2,@UserId3)) ',N'@UserId1 int,@UserId2 int,@UserId3 int',@UserId1=1,@UserId2=2,@UserId3=3

    执行该sql语句后报““,”附近有语法错误。”,看来就是生成的sql语句出了问题,去研究生成的sql语句就容易多了。

    原来生成的sql语句这里多了一对括号,引起了这个错误。

    去代码里面找这个括号是哪里来的,根据括号的位置尝试将自己代码中的括号去掉,修改自己的代码为:

     List<CICUser> userList = new List<CICUser>();
                using (IDbConnection conn = new SqlConnection(sqlConnectionString))
                {
                    int[] idarr = new int[] { 1, 2, 3 };
                    string sqlCommandText = @"SELECT * FROM CICUser s WHERE s.UserId IN @UserId ";
                    
                    userList = conn.Query<CICUser>(sqlCommandText, new { UserId = idarr },null,true,null, CommandType.Text).ToList();
                    
    
                }

    再去运行,成功了,跟踪得到sql语句:

    exec sp_executesql N'SELECT * FROM CICUser s WHERE s.UserId IN (@UserId1,@UserId2,@UserId3) ',N'@UserId1 int,@UserId2 int,@UserId3 int',@UserId1=1,@UserId2=2,@UserId3=3

    这下正常了,多的括号没有了。

    原来在做这样的查询时,参数不需要用括号括起来,dapper会给我们自动加上括号。

    @UserId
  • 相关阅读:
    King's Quest
    Prince and Princess
    Strongly connected
    线性渐变--linear-gradient
    镜像渐变-radio-gradient
    宽度自适应-左右
    宽度自适应-左中右
    HTML5 视频规范简介
    SVG格式
    Html5新标签解释及用法
  • 原文地址:https://www.cnblogs.com/fgq520328/p/11876462.html
Copyright © 2011-2022 走看看