Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how do i use group by only on date from datetime in LINQ query

i have this LINQ query

var data = (from orders in db.Orders
        group orders by orders.OrderDate into dateGroup
        select new OrderDateGroup()
        {
            OrderDate = dateGroup.Key,
            OrderCount = dateGroup.Count()
        }).Take(10);

orders.OrderDate is DateTime but i want to group only on the basis of Date

like image 585
Shri Avatar asked May 13 '15 13:05

Shri


People also ask

How can we do a group by using LINQ query?

You can also use Into Group with GroupBy in VB.Net. LINQ query is ended with the help Select or Groupby clause. It can also support method syntax in both C# and VB.Net languages. As shown in example 2.

What does Dbfunctions TruncateTime do?

TruncateTime(Nullable<DateTime>) When used as part of a LINQ to Entities query, this method invokes the canonical TruncateTime EDM function to return the given date with the time portion cleared.

What is let clause in LINQ?

The Let keyword allows you to create a range variable and initialized with the result of the query expression and then you are allowed to use that variable with the upcoming clause in the same query.

On which datasources do LINQ queries work?

In a LINQ query, you are always working with objects. You use the same basic coding patterns to query and transform data in XML documents, SQL databases, ADO.NET Datasets, . NET collections, and any other format for which a LINQ provider is available.


1 Answers

You can use canonical functions:

group orders by EntityFunctions.TruncateTime(orders.OrderDate) into dateGroup

Additional info:

EntityFunctions methods are called canonical functions. And these are a set of functions, which are supported by all Entity Framework providers. These canonical functions will be translated to the corresponding data source functionality for the provider. Canonical functions are the preferred way to access functionality outside the core language, because they keep the queries portable.

You can find all canonical functions here and all Date and Time Canonical Functions here.

Also, don't forget to include System.Data.Objects namepsace from System.Data.Entity.dll.

Note:
If you are using EF6, then you must consider to change EntityFunctions to DbFunctions. And don't forget to include System.Data.Entity namepsace from EntityFramework.dll.

like image 172
Farhad Jabiyev Avatar answered Oct 27 '22 01:10

Farhad Jabiyev