开发者

Constraining time with LINQ

I'm having difficulty constraining time in a LINQ statement. I am still pretty new with LINQ. The SQL I want to emulate is something like this:

SELECT ID, Token, StartTime 
FROM Tokens 
WHERE Token = '050' 
AND StartTime > DATEADD(MI, -30, CURRENT_TIMESTAMP)

This SQL statement gets only rows where the time in the StartTime column is less than 30 minutes from the current time. How would I do this with LINQ? So far my best guess is

DateTime cutoff = DateTime.Now - new Time开发者_如何学CSpan(0, 30, 0);
IEnumerable<Tokens> token = dataContext.Tokens.Where(row => row.Token == "050" && 
                                                            row.StartTime > cutoff);

But that doesn't seem to be working. Any advise?


You may add 30 days to token's StartTime and compare it to current date. You should probably also compare token text as string (double quotes), as it possibly might be a VARCHAR2 type.

var token = dataContext.Tokens.Where(r => 
  r.Token == "5" && 
  r.StartTime.AddDays(30).Date >= DateTime.Now.Date
);

Edit: probably you want to show last 30 days of operation, to do this date and time should be rounded to date - changed code.


row.Token == '5'

This jumps out at me. Watch out for using sql's string literal syntax in C#, as it indicates a char - not a string.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜