0

I've a very simple LINQ query to select dates from a table column - and I want to order by the date values:

var allDates = db.Table1.Select(m => m.Date).OrderBy(m => m.Date).Distinct();

But during runtime, I get the exception

"The specified type member 'Date' is not supported in LINQ to Entities."

In the model and the database, date-field is of type "DateTime". Selecting the values without ordering works fine.

Konrad
  • 4,329
  • 10
  • 54
  • 88

3 Answers3

3

You are selecting only the Date column, then you are trying to order by the property Date of this Date.

Instead:

var allDates = db.Table1.OrderBy(x => x.Date).Select(x => x.Date).Distinct();

or

var allDates = db.Table1.Select(x => x.Date).OrderBy(date => date).Distinct();

The order doesn't matter.


Update: Linq-To-Entities doesn't support the Date property of DateTime

If you need to truncate the time and you want to order by the date only, you could use EntityFunctions.TruncateTime:

var allDates = db.Table1.Select(x => EntityFunctions.TruncateTime(x.Date)).OrderBy(dt => dt).Distinct();
Community
  • 1
  • 1
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
2

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

DateTime.Date cannot be converted to SQL. Use EntityFunctions.TruncateTime method to get date part.

take a look at something like this:

var allDates = db.Table1.Select(m => DbFunctions.TruncateTime(m.Date)).OrderBy(date => date).Distinct();
Community
  • 1
  • 1
Misiakw
  • 902
  • 8
  • 28
0

You can do this way

var allDates = db.Table1.Select(m => m.Date).OrderBy(m => m.Value.Year)
                         .ThenBy(m => m.Value.Month)
                         .ThenBy(m => m.Value.Day).Distinct();
Mostafiz
  • 7,243
  • 3
  • 28
  • 42