Comparing Datetime? inside Linq Expression

1k views Asked by At

i am trying to return queries from a DB using Entity Framework and Linq on a Nullable DateTime field.

I have the following code;

DateTime? from = new DateTime(year, month, 1);
DateTime? to = from.Value.AddMonths(1);

return context.Where<Job>(
          x => 
          x.NextDueDate?.Date >= from?.Date &&
          x.NextDueDate?.Date <= to?.Date).ToList();

Where Job is (reduced for brevity);

public class Job : AuditableEntity
{
    ...
    public DateTime? NextDueDate { get; set; }

I tried this from the following stack link;

Linq expression with nullable DateTime

However, when I try this I am getting the following error;

An expression tree lambda may not contain a null propagating operator

Can anyone explain a solution to this please?

2

There are 2 answers

4
Win On BEST ANSWER

As the exception message said you cannot use ?.

// First day of a month. E.g. 2/1/2018 12:00:00 AM
DateTime from = new DateTime(year, month, 1);

// Last day of a month and end of that day. E.g. 2/28/2018 11:59:59 PM
DateTime to = from.AddMonths(1).AddTicks(-1); 

return context.Where<Job>(
    x =>
        x.NextDueDate != null &&
        x.NextDueDate >= from &&
        x.NextDueDate <= to).ToList();
0
Athul Nalupurakkal On

You are setting public DateTime? NextDueDate { get; set; }. So the default value won't be null.

Please try below code, because the date time value won't be null in code even when you fetch the null date time column from db. Which have a default value equal to 1/1/0001 12:00:00 AM.

DateTime from = new DateTime(year, month, 1);
DateTime to = from.Value.AddMonths(1);
DateTime dateTimeDefault = default(DateTime);

return context.Where<Job>(
          x =>  
          x.NextDueDate.Date != dateTimeDefault
          x.NextDueDate.Date >= from.Date &&
          x.NextDueDate.Date <= to.Date).ToList();