Basic SQL count with LINQ
I have a trivial issue that I can't resolve. Currently our app uses Linq to retrieve data and get a basic integer value of the row count. I can't form a query that gives back a count without a 'select i'. I don't need the select, just the count(*) response. How do I do this? Below is a sample:
return (from io in db._Owners
where io.Id == Id && io.userId == userId
开发者_高级运维 join i in db._Instances on io.Id equals i.Id **select i**).Count()
;
The select i
is fine - it's not actually going to be fetching any data back to the client, because the Count()
call will be translated into a Count(something)
call at the SQL side.
When in doubt, look at the SQL that's being generated for your query, e.g. with the DataContext.Log
property.
Using the LINQ query syntax requires a select
statement. There's no way around that.
That being said, the statement will get transformed into a COUNT()
-based query; the select i
is there only to satisfy the expression system that underlies the LINQ query providers (otherwise the type of the expression would be unknown).
Including the select will not affect the performance here because the final query will get translated into SQL. At this point it will be optimized and will be like select (*) from ......
精彩评论