How to compare DateTime without time via LINQ?

前端 未结 9 637
夕颜
夕颜 2020-12-08 18:03

I have

var q = db.Games.Where(t => t.StartDate >= DateTime.Now).OrderBy(d => d.StartDate);

But it compares including time part of

9条回答
  •  孤城傲影
    2020-12-08 18:56

    The .Date answer is misleading since you get the error mentioned before. Another way to compare, other than mentioned DbFunctions.TruncateTime, may also be:

    DateTime today = DateTime.Now.date;
    var q = db.Games.Where(t => SqlFunctions.DateDiff("dayofyear", today, t.StartDate) <= 0
          && SqlFunctions.DateDiff("year", today, t.StartDate) <= 0)
    

    It looks better(more readable) in the generated SQL query. But I admit it looks worse in the C# code XD. I was testing something and it seemed like TruncateTime was not working for me unfortunately the fault was between keyboard and chair, but in the meantime I found this alternative.

提交回复
热议问题