Distinct Date with Linq

I have an entity called Billings with a property of DateTime. I need to uniquely find the dates so I can go through them and do some stuff. I tried:

var DistinctYearMonthsDays = (from t in db.Billings 
                              where t.DateTime.HasValue 
                              select   t.DateTime.Value.Date).Distinct();

foreach (var day in DistinctYearMonthsDays)

but I get (on the foreach):

The specified type member 'Date' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.

After searching I also tried the following without success:

IEnumerable<DateTime> DistinctYearMonthsDays = db.Billings
    .Select(p => new 
        {              
            p.DateTime.Value.Date.Year,
            p.DateTime.Value.Date.Month,
            p.DateTime.Value.Date.Day 
         }).Distinct()
         .ToList()
         .Select(x => new DateTime(x.Year,x.Month,x.Day));

Any help will be very much appreciated.

Answers


You can use the built in EntityFunctions. Your query would become:

var DistinctYearMonthsDays = (from t in db.Billings 
                              where t.DateTime.HasValue 
                              select EntityFunctions.TruncateTime(t.DateTime)).Distinct();

For more about EntityFunctions, check MSDN.


Need Your Help

ProviderKey from ADFS changes when application restarts

asp.net owin adfs ws-federation

We've got our ASP.NET application configured to use multiple providers (Google, Microsoft, LinkedIn, and ADFS) with OWIN. When any of the providers other than ADFS authenticate, the ExternalLoginIn...

getting mean value of sensor for given runs

matlab mean

given A number of sensor values measured at each of 100 runs.