Entity Framework query not returning correctly enumerated results.

Posted by SkippyFire on Stack Overflow See other posts from Stack Overflow or by SkippyFire
Published on 2010-03-22T19:30:25Z Indexed on 2010/03/22 19:31 UTC
Read the original article Hit count: 619

I have this really strange problem where my entity framework query isn't enumerating correctly.

The SQL Server table I'm using has a table with a Sku field, and the column is "distinct". It isn't a key, but it doesn't contain any duplicate values. Using actual SQL with where, distinct and group by cluases I have confirmed this.

However, when I do this:

// Not good
foreach(var product in dc.Products)

or

// Not good
foreach(var product in dc.Products.ToList())

or

// Not good
foreach(var product in dc.Products.OrderBy(p => p.Sku))

the first two objects that are returned ARE THE SAME!!!

The third item was technically the second item in the table, but then the fourth item was the first row from the table again!!!

The only solution I have found is to use the Distinct extension method, which shouldn't really do anything in this situation:

// Good
foreach(var product in dc.Products.ToList().Distinct())

Another weird thing about this is that the count of the resulting queries is the same!!! So whether or not the resulting enumerable has the correct results or duplicates, I always get the number of rows in the actual table! (No I don't have a limit clause anywhere).

What could possibly cause this!?!?!?

© Stack Overflow or respective owner

Related posts about entity-framework

Related posts about LINQ