Skip to content
Advertisement

Linq tolist() count returns different value from translated sql

I have a situation where the translated sql direct form Visual Studio is returning a different number of records from the Linq. I am expecting 4 items but in the count() of the resulting list I only have 1. This is the case despite creating more records – it always returns 1.

db.DCLVUnknowns.Where(x => x.DCLVUnknownId == Report.DCLid).ToList();

SELECT 
[Extent1].[DCLVUnknownId] AS [DCLVUnknownId], 
[Extent1].[Gender] AS [Gender], 
[Extent1].[Height] AS [Height], 
[Extent1].[Weight] AS [Weight],
[Extent1].[Age] AS [Age],
[Extent1].[Race] AS [Race],
[Extent1].[DCLid] AS [DCLid] 
FROM [dbo].[DCLVUnknown] AS [Extent1]

Strange thing is I have the same linq expression running fine for other entities and there is no problem. It is consistently happening at the same spot every time.

enter image description here

Advertisement

Answer

db.DCLVUnknowns

Is a query of the entire table, not the query for what you want.

If you want to inspect the IQueryable of the full query, try:

var results = db.DCLVUnknowns.Where(x => x.DCLVUnknownId == Report.DCLid);
var theResultSet = results.ToList();

Here results should translate as roughly:

SELECT 
[Extent1].[DCLVUnknownId] AS [DCLVUnknownId], 
[Extent1].[Gender] AS [Gender], 
[Extent1].[Height] AS [Height], 
[Extent1].[Weight] AS [Weight],
[Extent1].[Age] AS [Age],
[Extent1].[Race] AS [Race],
[Extent1].[DCLid] AS [DCLid] 
FROM [dbo].[DCLVUnknown] AS [Extent1]
WHERE [Extent1].[DCLVUnknownId] = DCLid

Assuming DCLVUnknownId is a PK/ Identity, you should see one result in theResultSet.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement