Question

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?

Was it helpful?

Solution

Since you're using LINQ to Entities rather than LINQ to SQL, the question you're referencing doesn't apply. You can just use row.FirstActivityTime == myDate in your filter and EF will generate the correct SQL query, incorporating an is null check along with the equality check.

EDIT

It turns out this behavior has been changed a bit, and you need to set a flag on the context to get the old behavior back. (source: http://entityframework.codeplex.com/workitem/178)

var objectContext = ((IObjectContextAdapter)dbContext).ObjectContext;
objectContext.ContextOptions.UseCSharpNullComparisonBehavior = true;

After doing that, the is null checks will be included in the generated SQL.

OTHER TIPS

You should write this:

var q = from row in db.Activities 
        where (mydate.HasValue && 
            DateTime.Equals(row.FirstActivityTime, myDate.Value))
        select row;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top