gpt4 book ai didi

asp.net-core - 在 .Net Core API 中使用 Dapper 选择计数 (*) 查询返回不正确的值

转载 作者:行者123 更新时间:2023-12-05 08:30:32 25 4
gpt4 key购买 nike

我正在尝试使用 Dapper 在 Sql Server 中执行选择计数查询。当配置文件不存在时,预期响应应为 0。当我在 SSMS 中执行查询时,它会正确返回,但在使用 Dapper 的 API 中它会返回 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);
}

最佳答案

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

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 注入(inject)攻击。您的初始示例非常脆弱!

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

关于asp.net-core - 在 .Net Core API 中使用 Dapper 选择计数 (*) 查询返回不正确的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63769478/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com