Select Count(*) Query using Dapper in .Net Core API returns 不正确的值

Select Count(*) Query using Dapper in .Net Core API returns incorrect value

我正在尝试使用 Dapper 在 Sql 服务器中执行 select 计数查询。当配置文件不存在时,预期响应应为 0。当我在 SSMS 中进行查询时 returns 正确,但在 API 中使用 Dapper 时 returns 1. 知道为什么会这样吗?

public IActionResult GetProfileCount(string profileId)
    {
        int profileCount = 0;
        using (IDbConnection db = new SqlConnection(connectionString))
        {
            try
            {
                profileCount = db.Query($"select count(*) from Profile where Id='{profileId}'").Count();
            }
            catch(Exception ex)
            {
                Console.WriteLine($"Error retrieving count for ProfileId: {profileId}", ex.Message);
            }
        }

        return Ok(profileCount);
    }

尝试将您的查询更改为以下内容:

db.Query($"select count(*) from Profile where Id = @ProfileId", new { ProfileId = profileId }).Count()

我明白了。 .Count() 正在计算结果的行数,这将是 1,因为结果 显示数字 0 的一行。我将我的代码切换到这个并且它现在可以工作.

public IActionResult GetProfileCount(string profileId)
{
    int profileCount = 0;
    using (IDbConnection db = new SqlConnection(connectionString))
    {
        try
        {
            profileCount = db.Query($"select * from Profile where Id='{profileId}'").Count();
        }
        catch(Exception ex)
        {
            Console.WriteLine($"Error retrieving count for ProfileId: {profileId}", ex.Message);
        }
    }

    return Ok(profileCount);
}

我看到您添加了自己的答案,但我可以建议不要那样做吗?当你这样做时

profileCount = db.Query($"select * from Profile where Id='{profileId}'").Count();

您实际做的是从数据库中选择每个字段,将其拉入您的 C# 应用程序,然后计算返回的结果数量。然后你把你得到的所有数据装箱,效率很低!

改成这样:

profileCount = db.QueryFirst<int>($"select count(*) from Profile where Id = @profileId", new { profileId })");

相反,您从结果集中选择了一个“int”,它恰好是您的计数 (*)。完美!

更多关于在 Dapper 中查询的信息:https://dotnetcoretutorials.com/2019/08/05/dapper-in-net-core-part-2-dapper-query-basics/

另请注意(与其他答案类似),我正在使用参数化查询。我也强烈推荐这个,因为它可以保护你免受 SQL 注入。您的初始示例非常脆弱!

您可以在此处阅读更多关于 SQL C#/MS 中的注入 SQL https://dotnetcoretutorials.com/2017/10/11/owasp-top-10-asp-net-core-sql-injection/ 但只要您使用内置的帮助程序,Dapper 就会保护您免受它的侵害为您的查询添加参数。

另一种选择是使用 ExecuteScalar 方法进行 "select 计数" 查询:

profileCount = db.ExecuteScalar<int>("select count(*) from Profile where Id=@profileId", new { profileId });

参考:https://www.learndapper.com/selecting-scalar-values