尽管有查询字符串,但在使用 sql COUNT 时 ExecuteNonQuery 返回 -1

ExecuteNonQuery returning -1 when using sql COUNT despite the query string

出于某种原因,ExecuteNonQuery() 在 C# returns -1 中,虽然当我 运行 单独查询时,值 returns 实际需要的值.

例如:

try
{

    var connString ="Data Source=ServerName;InitialCatalog=DatabaseName;Integrated Security=true;"
    SqlConnection conn = new SqlConnection(connString);

    SqlCommand someCmd = new SqlCommand("SELECT COUNT(*) FROM SomeTable");

    someCmd.Connection = conn;

    conn.Open();

    var theCount = cmd.ExecuteNonQuery();

    conn.Close();
}
catch(Exception ex)
{
    Console.WriteLine(ex.Message);
}

当命令执行时 returns -1。虽然如果 运行 单独查询,

SELECT COUNT(*) FROM SomeTable;
如果要查询的 table 有 4 行,则

列 returns 一行的计数为 4

基于MSDN

For UPDATE, INSERT, and DELETE statements, the return value is the number of rows affected by the command. When a trigger exists on a table being inserted or updated, the return value includes the number of rows affected by both the insert or update operation and the number of rows affected by the trigger or triggers. For all other types of statements, the return value is -1. If a rollback occurs, the return value is also -1.

您想 return 受命令影响的行数并将其保存到 int 变量但是由于语句类型是 select 所以它 returns -1.

解决方案:如果你想获得受SELECT命令影响的行数并将其保存到一个int变量中,你可以使用ExecuteScalar .

var theCount = (int)cmd.ExecuteScalar();

您可以将 Ef 核心与 Ado.net 一起使用,就像这个例子

var context = new SampleDbContext();
using (var connection = context.Database.GetDbConnection())
{
    connection.Open();

    using (var command = connection.CreateCommand())
    {
        command.CommandText = "SELECT COUNT(*) FROM SomeTable";
        var result = command.ExecuteScalar().ToString();
    }
}