views:

66

answers:

1

I'm really confused by a behaviour of LINQ I'm seeing and it's causing me a problem.

I wrote a query like:

var reportalerts = pushDB.ReportAlerts
                         .Select(p => new {p.Title, p.Url, p.DateStamp})
                         .OrderBy(p => p.DateStamp)
                         .Take(numResultsPerPage);

This creates the SQL that I'd expect:

SELECT TOP (5) [t0].[Title], [t0].[Url], [t0].[DateStamp]
FROM [dbo].[ReportAlerts] AS [t0]
ORDER BY [t0].[DateStamp]

If I then add an extra property to my anonymous type, the sql generated is radically different:

var reportalerts = pushDB.ReportAlerts
                         .Select(p => new {p.Title, p.Url, p.DateStamp, p.Text})
                         .OrderBy(p => p.DateStamp)
                         .Take(numResultsPerPage);

Becomes:

SELECT TOP (5) [t0].[Title], [t0].[Url], [t0].[DateStamp], [t0].[PushReportAlertID], [t0].[DateOfAlert], [t0].[AlertProductID], [t0].[Description], [t0].[Mpid], [t0].[UIName], [t0].[CustomerDesc], [t0].[ProductArea]
FROM [dbo].[ReportAlerts] AS [t0]
ORDER BY [t0].[DateStamp]

That is it takes every column from the table now. It's like it has decided, this guy is selecting enough columns for me to just go and grab all of them now. This is a problem for me as I want to concat (i.e. UNION ALL) the query with a similar one from another table which has different columns. (before the order by/take) If it would take only the columns that are specified by my anonymous type properties it would not be a problem, but as it takes all the columns and the two tables have differing columns, it fails.

I can solve the problem in various different ways, so I'm not stopped by this, I just want to understand what is happening above, and if there is not a way you can get it to just return the columns you want.

A: 

Gar, it's because I'm an idiot.

The problem is that Text is not a property on the table, it is there to satisfy an interface and actually returns another property which is part of the table.

Changing the above to:

var reportalerts = pushDB.ReportAlerts
                         .Where(p => subscribedMpids.Contains(p.Mpid))
                         .Select(p => new {p.Title, p.Url, p.DateStamp, Text = p.Description})
                         .OrderBy(p => p.DateStamp)
                         .Take(numResultsPerPage);

Works as expected.

Andrew Barrett