Great date with Linq

I have an object called Billings with a DateTime property. I need to unequivocally find the dates so that I can go through them and do some things. 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 foreach):

The specified member of type 'Date' is not supported in LINQ to Entities. Only initializers, entities, 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 would be greatly appreciated.

+5
source share
1 answer

You can use the built-in EntityFunctions. Your request will look like this:

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

For more on EntityFunctions, check out MSDN .

+8
source

All Articles