The Jonas Persson
The Jonas Persson

Reputation: 1746

Comparing a nullable datetime to a datetime using Linq to EF

I have a database table field that is a nullable datetime. For some reason I can get the query below to work.

var requests = _db.Requests
               .Where(r => r.processedDate.Value == processDate);

I am 100% sure that I have four matching dates, but I keep getting nothing back. I have tried all kinds of variations on this query, but without success.

Update

The reason the compare doesn't work is that I am passing the processDate through a javascript function, like this

function Reprocess(processDate, spanid) {
    if(confirm('Are you sure you want to re-process this batch?')) {
        $.ajax({
            type: "Post",
            url: "?ajaxFunction=Reprocess",
            data: processDate,
            success: function (data, textStatus, jqXHR) {
                $(spanid).html(data);
            }
        });
    }
}

When I do, I am forced to convert the DateTime to a string in order to pass it to my function. When I convert it to a string it rounds of to seconds, and hence loses the miliseconds. Which is why the Linq query doesn't find any matches (because of 14 milliseconds).

How can I pass the full datetime value through javascript? Or will I have to compare on date, hour, minute, and second instead?

Upvotes: 0

Views: 1818

Answers (1)

Alexander Schimpf
Alexander Schimpf

Reputation: 2392

If you're converting it to a string server-side, before it gets to your JavaScript, then try this:

C#

// Make sure processDateStr gets to your JavaScript function
string processDateStr = processDate.ToString("o");

And then when you get the string value back on the server again, use this to restore the same value:

DateTime processDate = DateTime.Parse(processDateStr, null, DateTimeStyles.RoundtripKind);

The value will be restored exactly as it was originally.

EDIT

The "o" format specifier is the round-trip specifier. You can read more about it here on MSDN.

Upvotes: 1

Related Questions