Bob Waldorf
Bob Waldorf

Reputation: 1

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()

;

Upvotes: 0

Views: 369

Answers (3)

Nasmi Sabeer
Nasmi Sabeer

Reputation: 1380

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 ......

Upvotes: 0

Adam Robinson
Adam Robinson

Reputation: 185643

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).

Upvotes: 1

Jon Skeet
Jon Skeet

Reputation: 1500575

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.

Upvotes: 3

Related Questions