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?
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 ;
.
count
ends with group by my_col_id
Dec 18, 2020 at 15:47
GROUP BY
and a COUNT
in the raw SQL query. Just writing a SELECT *
and performing a CountAsync()
in C# generates exactly the query I needed. Also, FromSqlRaw
returns an IQueryable
, meaning no data is returned to the client at this point. The SQL query is executed only when we reach the CountAsync()
instruction.
May 17, 2021 at 9:39
the fastest hack/workaround is if your Item class has an int/long property (lets say Id) you can treat it like this:
dbContext.Items.FromSql("SELECT COUNT(*) as Id
FROM Items
WHERE JSON_VALUE(Column, '$.json') = 'abc'").Select(x=>x.Id).First();
You should pass composable SELECT
SQL to FromSql
method, e.g. SELECT *
- see Raw SQL Queries. Then you can apply regular LINQ Queryable
operators, including Count
:
var count = dbContext.Items
.FromSql("select * FROM Items Where JSON_VALUE(Column, '$.json') = 'abc'")
.Count();
SELECT Count(*) FROM (your select SQL here)
Nov 7, 2018 at 17:24
FromSql
just because you need JSON_VALUE
function. Then you may find this stackoverflow.com/questions/52017204/… interesting, because it allows you to use regular LINQ query with all its benefits.
Nov 7, 2018 at 17:27
You can do something like:
dbContext.Items.Count()
You always can do a .Count()
Function on an IQueryable
Edit: When the need of a FromSql is really there something like this should do the job:
var count = context.Items.FromSql("Select count(*) from items").First();
var count = context.Items.FromSql("Select count(*) from items").First();
FromSQL has some limitations:
So, try this:
var elements = dbContext.Items
.FromSql("SELECT * from dbo.Items")
.ToList();
var countOfElements = elements.Count();
db.Items.Count()
: