Skip to content

Count after Take throws "No column name was specified for column 1 of 't'." #29667

@ditchcode

Description

@ditchcode

I found similar closed issues surrounding Count with subqueries.

I discovered this passing a Linq query into a 3rd party library which internally performs a Count on the query it is given.

EF Core 7.0 Repro:
Perform a Take(25).CountAsync() on any context DbSet.

You wind up with

exec sp_executesql N'SELECT COUNT(*)
FROM (
    SELECT TOP(@__p_0) 1
    FROM [SomeTable] AS [c]
) AS [t]',N'@__p_0 int',@__p_0=25

Which throws database error "No column name was specified for column 1 of 't'"

This could easily be resolved by adding a column name AS [t](x), such as:

exec sp_executesql N'SELECT COUNT(*)
FROM (
    SELECT TOP(@__p_0) 1
    FROM [SomeTable] AS [c]
) AS [t](x)',N'@__p_0 int',@__p_0=25

EF Core 6.0 does not have this issue as it produces
SELECT TOP(@__p_0) [c].[Column1],[c].[Column2],.....
It seems in 7.0, it was decided to simplify the Count by removing the SELECT fields and just using a hard-coded 1.
SELECT TOP(@__p_0) 1

Metadata

Metadata

Assignees

Type

Projects

No projects

Milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions