finding out if a linq table has 0 rows

A

Andy B

How would you find out if a linq table has 0 rows in it? I have this code:

NewsContext.V_News() '*** linq table to be tested for 0 rows

Any ideas?
 
B

bruce barker

linq to sql queries are only executed when you foreach the results. as a
datareader is used the row count is not known until all rows are read.
so the easiest is convert the query to an array. you then have both the
data and the row count (array size) at that point.

if you just need a row count, then don't use linq, as it has to read all
the rows and count them. add a method to the context that uses a
sqlcommand and count(*) to get the rowcount. sqlserver in this case will
do the count much faster.

note- in linq to sql, every time you foreach the query, its run again

-- bruce (sqlwork.com)
 
A

Andy B

"linq to sql queries are only executed when you foreach the results."
IEnumerable. Makes sense.

"as a datareader is used the row count is not known until all rows are
read."
Does linq make extensive use of dataReader internally?

"so the easiest is convert the query to an array."
Will keep it in mind for later if I need it.

"you then have both the data and the row count (array size) at that point."
Good way to do it if you need the results and the count. Doesn't linq have
something like this:
'*** query the v_news linq table
NewsContext.CreateQuery("select count(*) from v_news")

"if you just need a row count, then don't use linq, as it has to read all
the rows and count them. add a method to the context that uses a sqlcommand
and count(*) to get the rowcount. sqlserver in this case will do the count
much faster."
I think I will use this instead. Just trying to prevent a trip to the server
just for that.

"note- in linq to sql, every time you foreach the query, its run again"

Except when using data functions that are linked to sql procedures and
functions.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
473,763
Messages
2,569,562
Members
45,039
Latest member
CasimiraVa

Latest Threads

Top