10

I have a PostgreSQL database that interacts with the program through Entity Framework Code First.

Database contains a table "users" that has column "visit" type of DateTime.

The application is described as;

public class Users
{    ...
    [Required]
    [Column("visit")]
    public DateTime VisitDate
    ...
}

I trying to run this query;

var rslt = context.Visitors.Where(v => v.VisitDate.Date == DateTime.Now.Date).ToList()

But getting an exception: NotSupportedException

What's wrong?

Dave S.
  • 6,349
  • 31
  • 33
max
  • 115
  • 1
  • 1
  • 8

4 Answers4

13

Use the class EntityFunction for trimming the time portion.

using System.Data.Objects;    

var bla = (from log in context.Contacts
           where EntityFunctions.TruncateTime(log.ModifiedDate) ==  EntityFunctions.TruncateTime(today.Date)
           select log).FirstOrDefault();

Source: http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/84d4e18b-7545-419b-9826-53ff1a0e2a62/

Mayur Borad
  • 1,295
  • 9
  • 23
11

DateTime.Date property is not supported. You have to use SqlFunctions.DatePart method instead. It will end up with DATEPART TSQL method within generated SQL query.

var rslt = context.Visitors
                  .Where(v => SqlFunctions.DatePart("year", v.VisitDate) == SqlFunctions.DatePart("year", DateTime.Now))
                  .Where(v => SqlFunctions.DatePart("dayofyear", v.VisitDate) == SqlFunctions.DatePart("dayofyear", DateTime.Now))
                  .ToList(); 
keeehlan
  • 7,874
  • 16
  • 56
  • 104
MarcinJuraszek
  • 124,003
  • 15
  • 196
  • 263
  • 2
    Thanks for you answer, but I get NotSupportedException again. But message contains other information: The specified method 'System.Nullable`1[System.Int32] DatePart(System.String, System.Nullable`1[System.DateTime])" on the type "System.Data.Objects.SqlClient.SqlFunctions" cannot be translated into a LINQ to Entities store expression. Maybe it's PostgreSQL's problem? – max May 24 '13 at 15:20
5

Mayur Borad's answer (IMHO more correct than the accepted answer) has become out of date:

System.Data.Entity.Core.Objects.EntityFunctions is obsolete. You should use System.Data.Entity.DbFunctions instead.

var today = DateTime.Today; // (Time already removed)

var bla = context.Contacts
    .FirstOrDefault(x => DbFunctions.TruncateTime(x.ModifiedDate) == today);
Tim S
  • 2,309
  • 16
  • 23
3

The problem is that the LINQ provider is trying to convert DateTime.Now.Date to a database method, which it cannot do by default. The trick to doing date comparison is to create a DateTime instance that has its time component set to the default value. You can get more information here and here.

Community
  • 1
  • 1
Erik Schierboom
  • 16,301
  • 10
  • 64
  • 81