LINQ: Nullable value types in where clause

Viewed 1562

I'm trying to query a table with possible NULL values. According to this question, using object.Equals is the way to do it:

DateTime? myDate = null;
var q =
    from row in db.Activities
    where object.Equals(row.FirstActivityTime, myDate)
    select row;

This works, but when I assign a non null value to myDate,

DateTime? myDate = DateTime.Now;

it all falls apart and throws the exception "Unable to cast the type 'System.Nullable`1' to type 'System.Object'. LINQ to Entities only supports casting EDM primitive or enumeration types".

I could rewrite the where clause into

where row.FirstActivityTime == myDate || (row.FirstActivityTime == null && myDate == null)

but is there any way to make this work with object.Equals?

2 Answers
Related