I have
dbContext.Items.FromSql("SELECT COUNT(*)
FROM Items
WHERE JSON_VALUE(Column, '$.json') = 'abc'")
This returns an IQueryable
, I am wondering how I can return a scalar int
back?
Use the COUNT aggregate function to count the number of rows in a table. This function takes the name of the column as its argument (e.g., id ) and returns the number of rows for this particular column in the table (e.g., 5).
Counting all of the Rows in a Table. To counts all of the rows in a table, whether they contain NULL values or not, use COUNT(*). That form of the COUNT() function basically returns the number of rows in a result set returned by a SELECT statement.
var count = dbContext.Set.FromSqlRaw(/* {raw SQL} */).Count();
Will generate the following SQL
SELECT COUNT(*)::INT
FROM (
-- {raw SQL}
) AS c
where {raw SQL}
is of the form
select count(*) from my_table where my_col_condition = true group by my_col_id
The count work can then perfectly be done on the database-side this way, without loading table rows on the client.
Be careful not to end {raw SQL}
with ;
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With