Date received from a NULL date?

I declared the field in my model as a NULL value like this

public DateTime? CallNextDate {get;set;} 

in my aspx code behind I use this linq as follows:

 q = q.AsQueryable() .Where(c => c.CallNextDate.Date < DateTime.Now.Date ) .ToList(); 

but c.CallNextDate.Date not available. Please suggest how to fix this.

+7
source share
2 answers

Well, if you already know that this is not null, you can use Value to get a base value other than zero:

 q = q.AsQueryable() .Where(c => c.CallNextDate.Value.Date < DateTime.Now.Date) .ToList(); 

Or, if you want to filter this as well:

 q = q.AsQueryable() .Where(c => c.CallNextDate.Value != null && c.CallNextDate.Value.Date < DateTime.Now.Date) .ToList(); 

I would highly recommend that you get the date once today and reuse it for the entire request:

 var today = DateTime.Today; q = q.AsQueryable() .Where(c => c.CallNextDate.Value != null && c.CallNextDate.Value.Date < today) .ToList(); 

This will give you more consistency. You should really consider whether, of course, you want a system local date, by the way.

(You definitely need to use AsQueryable , by the way? It's relatively rare.)

+16
source

Nullable types have a Value property that represents the base type:

 q = q.AsQueryable() .Where(c => c.CallNextDate.Value.Date < DateTime.Now.Date ) .ToList(); 

But you need to check that the type matters.

 q = q.AsQueryable() .Where(c => c.CallNextDate.HasValue && c.CallNextDate.Value.Date < DateTime.Now.Date ) .ToList(); 
+5
source

All Articles