Linq2DB adding unnecessary statements to query when grouping by two parts of a date.
See original GitHub issueI am trying to generate a query that gets the number of entries with dates that occur within each given month. The SQL form of the query I wish to generate goes like this:
SELECT
DatePart(Year, [t1].[StartTime]) as Year,
DatePart(Month, [t1].[StartTime]) as Month,
Count(*) as 'Visits',
Sum([t1].[PageCount]) as 'Total Pageviews'
FROM
[MyDatabase] [t1]
GROUP BY
DatePart(Year, [t1].[StartTime]),
DatePart(Month, [t1].[StartTime])
I tried the following Linq2DB code:
var query = from table in dataContext.MyDataContext(tablePath)
group table by new { table.StartTime.Year, table.StartTime.Month} into grp
select new { Month = grp.Key.Month, Year = grp.Key.Year,
TotalVisitors = grp.Count(),
TotalPageviews = grp.Sum(table2 => table2.PageCount) };
but the SQL query being generated by this is
-- SqlServer.2008 --
SELECT
[t1].[StartTime],
Count(*) as [c1],
Sum([t1].[PageCount]) as [c2]
FROM
[MyDatabase] [t1]
GROUP BY
DatePart(Year, [t1].[StartTime]),
DatePart(Month, [t1].[StartTime]),
[t1].[StartTime]
Why is [t1].[StartTime] rather than the month or year? And why is it grouping by that extra [t1].[StartTime] at the end? How do I generate the SQL query I have above using Linq2DB?
Issue Analytics
- State:
- Created 6 years ago
- Comments:5 (4 by maintainers)
Top Results From Across the Web
Linq2Db / Access - error with anonymous group by multiple ...
I try to select top 5 users from table pob based on their last activity date. So I inner join names and pob...
Read more >8 Tips and Tricks for Writing the Best Queries in LINQ to ...
This blog post provides a few tips and best practices to consider when writing LINQ to Entities to ensure they run quickly and...
Read more >[Solved]-Linq2DB adding unnecessary statements to query-LINQ,C#
var query = from table in dataContext.MyDataContext(tablePath) group table by new { Sql.AsSql(table.StartTime.Year), Sql.AsSql(table.StartTime.
Read more >LINQ to DB | Linq To DB
LINQ to DB is the fastest LINQ database access library offering a simple, light, fast, and type-safe layer between your POCO objects and...
Read more >Writing Better Performing Queries with LINQ on EF Core 6.0 ⚙️
When loading related one-to-many entities, EF Core adds ORDER BY clauses to make sure all related entities for a given entity are grouped...
Read more >
Top Related Medium Post
No results found
Top Related StackOverflow Question
No results found
Troubleshoot Live Code
Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free
Top Related Reddit Thread
No results found
Top Related Hackernoon Post
No results found
Top Related Tweet
No results found
Top Related Dev.to Post
No results found
Top Related Hashnode Post
No results found
@dimensional-difficulties, i have another solution. It works but not so clear as expected Use function
Sql.AsSql
Duplicate of #264