views:

259

answers:

2

I'm in the midst of trying to replace a the Criteria queries I'm using for a multi-field search page with LINQ queries using the new LINQ provider. However, I'm running into a problem getting record counts so that I can implement paging. I'm trying to achieve a result equivalent to that produced by a CountDistinct projection from the Criteria API using LINQ. Is there a way to do this?

The Distinct() method provided by LINQ doesn't seem to behave the way I would expect, and appending ".Distinct().Count()" to the end of a LINQ query grouped by the field I want a distinct count of (an integer ID column) seems to return a non-distinct count of those values.

I can provide the code I'm using if needed, but since there are so many fields, it's pretty long, so I didn't want to crowd the post if it wasn't needed.

Thanks!

A: 

You could try selecting the column you want a distinct count of first. It would look something like: Select(p => p.id).Distinct().Count(). As it stands, you're distincting the entire object, which will compare the reference of the object and not the actual values.

Correl
A good idea, and one that I tried. Unfortunately, that doesn't seem to work the way I would expect. In my situation, there are actually 27 distinct IDs in the table, but doing this with all the joins I have in place returns something like 47,000. The query that doing a .Distinct().Count() generates doesn't actually have a "distinct" in it. Hopefully something that can be changed in a future version.
Brian Sullivan
A: 

I figured out a way to do this, though it may not be optimal in all situations. Just doing a .Distinct() on the LINQ query does, in fact, produce a "distinct" in the resulting SQL query when used without .Count(). If I cause the query to be enumerated by using .Distinct().ToList() and then use the .Count() method on the resulting in-memory collection, I get the result I want.

This is not exactly equivalent to what I was originally doing with the Criteria query, since the counting is actually being done in the application code, and the entire list of IDs must be sent from the DB to the application. In my case, though, given the small number of distinct IDs, I think it will work, and won't be too much of a performance bottleneck.

I do hope, however, that a true CountDistinct() LINQ operation will be implemented in the future.

Brian Sullivan
I just ran into the same issue. This seems to me like an issue with the LINQ adapter generating the wrong SQL. I had to use the same work-around as well, forcing the evaluation of the query with `ToList()` before doing a `Count()` on it.
Daniel T.