Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Linq to SQL: Where clause comparing a Nullable<DateTime> with a SQL datetime null column

Using C#, Linq to SQL, SQL Server, I have this:

MyTable has a column with a "datetime null" column.

DateTime? aDateTime;

var records = (from row in MyTable where row.StartDate == aDateTime);

And I noticed that the query does not do what I expected. Specifically, if aDateTime is null, it queries StartDate = null rather than StartDate IS null, which does not find records where the column value is null. Changing it to:

where aDateTime.HasValue ? (row.StartDate == aDateTime) : (row.StartDate == null)

works but is annoying. Is there a simpler solution to this problem?

like image 411
Scott Stafford Avatar asked Oct 10 '11 19:10

Scott Stafford


1 Answers

I think Object.Equals(row.StartDate, aDateTime) will do the trick.

There is lots about this on Google. For example, this post.

like image 134
James Avatar answered Nov 14 '22 22:11

James