I'm using two LINQ queries to access my database using Entity Framework:
The first stores a token in the database and gives it a 60 second timeout:
string tokenHash = GetTokenHash();
Token token = new Token()
{
Client = client,
Expiry = DateTime.Now.AddSeconds(60),
UserId = userId,
TokenHash = tokenHash,
};
context.AddToToken(token);
context.SaveChanges();
The second checks for a matching token that hasn't expired yet:
var item = (from t in datasource.SmsToken
where t.Client.Id == clientId
&& t.UserId == userId
&& t.TokenHash == tokenHash
&& t.Expiry > DateTime.Now
select t);
bool success = item.Count() >= 1;
The issue I'm having is that this was working perfectly on a test server. Now that it's moved to a different environment, it no longer works.
I've dumped a lot of debug information and everything seems to match. If I remove the t.Expiry > DateTime.Now
condition, it works fine. So the problem is in the date comparison.
The new server has been set up with different date format and globalization settings in Windows. I assume this is the problem, and this confuses me.
I would have thought that the dates would be stored and retrieved consistently using LINQ and EF. I shouldn't have any formatting issues with this should I? Can anyone tell me what's going wrong here?
Update:
Interestingly, I get correct behaviour by replacing the retrieval code with the following:
var item = (from t in datasource.SmsToken
where t.Client.Id == clientId
&& t.UserId == userId
// && t.TokenHash == tokenHash
// && t.Expiry > DateTime.Now
select t).ToList();
var matchingToken = (from t in item
where t.TokenHash == tokenHash
&& t.Expiry > DateTime.Now
select t).FirstOrDefault();
bool success = matchingToken != null;
That suggests to me that the problem is to do with date comparisons inside Linq-to-entities. Linq-to-objects works fine!