111

I got a exception while implementing the following statements.

 DateTime result;
 if (!DateTime.TryParse(rule.data, out result))
     return jobdescriptions;
 if (result < new DateTime(1754, 1, 1)) // sql can't handle dates before 1-1-1753
     return jobdescriptions;
 return jobdescriptions.Where(j => j.JobDeadline.Date == Convert.ToDateTime(rule.data).Date );

Exception

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

I know what the exception means but i don't know how to get rid of it. Any help?

1
  • This is in EF6 and lower. EF core supports .Date. Dec 4, 2019 at 11:33

9 Answers 9

240

You can use the TruncateTime method of the EntityFunctions to achieve a correct translations of the Date property into SQL:

using System.Data.Objects; // you need this namespace for EntityFunctions

// ...

DateTime ruleData = Convert.ToDateTime(rule.data).Date;
return jobdescriptions
    .Where(j => EntityFunctions.TruncateTime(j.JobDeadline) == ruleData);


Update: EntityFunctionsis deprecated in EF6, Use DbFunctions.TruncateTime

14
  • Well, i noticed that ruleData is DateTime type and j.JobDeadline has truncatedtime. Doesn't feel right. Didn't get exception but didn't get expected result as well.
    – nebula
    Jul 22, 2012 at 15:49
  • @aneal: It returns all records where JobDeadline has the same date as rule.data, no matter what's the time of the day. Isn't that what you want to achieve with your query in the question? Why doesn't it feel right?
    – Slauma
    Jul 22, 2012 at 16:25
  • 1
    +1 and i agree with above, is definitely a better answer for 99% of implementations
    – jim tollan
    Oct 28, 2013 at 16:06
  • 26
    Note that EntityFunctions is deprecated in EF6, you should now use DbFunctions.
    – Julien N
    Jan 8, 2014 at 14:15
  • 2
    Namespace for DbFunctions in > EF6 is System.Data.Entity : msdn.microsoft.com/en-us/library/Dn220142(v=VS.113).aspx
    – GraehamF
    Sep 12, 2015 at 22:58
105

LINQ to Entities cannot translate most .NET Date methods (including the casting you used) into SQL since there is no equivalent SQL.

The solution is to use the Date methods outside the LINQ statement and then pass in a value. It looks as if Convert.ToDateTime(rule.data).Date is causing the error.

Calling Date on a DateTime property also cannot be translated to SQL, so a workaround is to compare the .Year .Month and .Day properties which can be translated to LINQ since they are only integers.

var ruleDate = Convert.ToDateTime(rule.data).Date;
return jobdescriptions.Where(j => j.Deadline.Year == ruleDate.Year 
                       && j.Deadline.Month == ruleDate.Month 
                       && j.Deadline.Day == ruleDate.Day);
8
  • 6
    What about j => j.JobDeadline.Date ?
    – nebula
    Jul 22, 2012 at 3:45
  • 1
    Is Date a property on JobDeadline ? This shouldn't cause an error by itself - perhaps a naming conflict (but not sure on this). If the line is still causing an error just rename it DeadlineDate or similar.
    – Judo
    Jul 22, 2012 at 4:05
  • 1
    Date is property on JobDeadline. JobDeadline is DateTime type of which i want to extract Date.
    – nebula
    Jul 22, 2012 at 8:45
  • Then, to work this within LINQ you would need to just compare JobDeadline property, eg j.JobDeadline > ruleDate. This needs a bit of testing but can be made to work. Alternatively compare the three properties of .Month .Day and .Year (j.Deadline.Year == ruleDate.Year && j j.Deadline.Month == ruleDate.Month && j.Deadline.Day == ruleDate.Day). Not elegant but it works since these are only integers.
    – Judo
    Jul 22, 2012 at 9:06
  • Hmm. This idea works. Dirty but works. If you write it as answer i can mark it correct.
    – nebula
    Jul 22, 2012 at 15:46
39

For EF6 use DbFunctions.TruncateTime(mydate) instead.

10

"EntityFunctions.TruncateTime" or "DbFunctions.TruncateTime" in ef6 Is Working but it has some performance issue in Big Data.

I think the best way is to act like this:

DateTime ruleDate = Convert.ToDateTime(rule.data);

DateTime  startDate = SearchDate.Date;

DateTime  endDate = SearchDate.Date.AddDay(1);

return jobdescriptions.Where(j.Deadline >= startDate 
                       && j.Deadline < endDate );

it is better than using parts of the date to. because query is run faster in large data.

1
  • +1 for this answer. EntityFunctions.TruncateTime (later replaced by DbFunctions.TruncateTime) are implemented by converting to SQL where the datetime is converted to a string and that is truncated. This makes the query run significantly slower, in proportion to the number of records processed.
    – urig
    Mar 21, 2017 at 13:08
3

Need to include using System.Data.Entity;. Works well even with ProjectTo<>

var ruleDate = rule.data.Date;
return jobdescriptions.Where(j => DbFunctions.TruncateTime(j.Deadline) == ruleDate);
1
1

What it means is that LINQ to SQL doesn't know how to turn the Date property into a SQL expression. This is because the Date property of the DateTime structure has no analog in SQL.

1

It worked for me.

DateTime dt = DateTime.Now.Date;
var ord = db.Orders.Where
      (p => p.UserID == User && p.ValidityExpiry <= dt);

Source: Asp.net Forums

0
0

I have the same problem but I work with DateTime-Ranges. My solution is to manipulate the start-time (with any date) to 00:00:00 and the end-time to 23:59:59 So I must no more convert my DateTime to Date, rather it stays DateTime.

If you have just one DateTime, you can also set the start-time (with any date) to 00:00:00 and the end-time to 23:59:59 Then you search as if it were a time span.

var from = this.setStartTime(yourDateTime);
var to = this.setEndTime(yourDateTime);

yourFilter = yourFilter.And(f => f.YourDateTime.Value >= from && f.YourDateTime.Value <= to);

Your can do it also with DateTime-Range:

var from = this.setStartTime(yourStartDateTime);
var to = this.setEndTime(yourEndDateTime);

yourFilter = yourFilter.And(f => f.YourDateTime.Value >= from && f.YourDateTime.Value <= to);
0

As has been pointed out by many here, using the TruncateTime function is slow.

Easiest option if you can is to use EF Core. It can do this. If you can't then a better alternative to truncate is to not change the queried field at all, but modify the bounds. If you are doing a normal 'between' type query where the lower and upper bounds are optional, the following will do the trick.

    public Expression<Func<PurchaseOrder, bool>> GetDateFilter(DateTime? StartDate, DateTime? EndDate)
    {
        var dtMinDate = (StartDate ?? SqlDateTime.MinValue.Value).Date;
        var dtMaxDate = (EndDate == null || EndDate.Value == SqlDateTime.MaxValue.Value) ? SqlDateTime.MaxValue.Value : EndDate.Value.Date.AddDays(1);
        return x => x.PoDate != null && x.PoDate.Value >= dtMinDate && x.PoDate.Value < dtMaxDate;
    }

Basically, rather than trimming PoDate back to just the Date part, we increment the upper query bound and user < instead of <=

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.