Dapper 执行返回-1 值?

Pat*_*han 3 sql-server dapper

当给定值可用时,以下 SQL 查询返回 1;当给定值不可用时,以下 SQL 查询返回 0,并且它在 SQL Server Management Studio 中工作正常,

select 
    case 
       when exists (select * from [dbo].[user] 
                    where userName = 'admin' 
                      and password = 'admin') 
          then cast(1 as bit) 
          else cast(0 as bit)
    end
Run Code Online (Sandbox Code Playgroud)

使用 dapper ORM 的相同查询如下:

public int login(string userName, string password)
{
        string sql = "select case when exists(select * from user where userName = @usernamepara and password = @passwordpara) then cast(1 as bit) else cast(0 as bit )end";

        using(IDbConnection conn = dbConnection)
        {
            conn.Open();

            var res = conn.Execute(sql, 
                                   param: new { usernamepara = userName, 
                                                passwordpara = password });
            conn.Close();
            return res;
        }
    }
Run Code Online (Sandbox Code Playgroud)

但是当调用这个方法时,对于匹配和不匹配的记录,它都会返回-1。这是怎么回事?

Cai*_*ard 5

可能是因为您使用了错误的执行:

https://dapper-tutorial.net/execute

说 EXECUTE 将返回受影响的行数,并且该文档明确指出,execute 不用于返回行的查询

我想说你应该在 dapper 中使用一些在后台使用 ExecuteScalar 的东西 - 请参阅Dapper 中是否有 ExecuteScalar以及我对问题的评论中的链接,了解如何转动计数查询(也在评论中建议) int 一个图书结果,其中 0 为假,其他为真