在我的 Web 應用程式中,我只想顯示 2 天前從“DateTime.Today”記錄的資料。
獲取我嘗試過的 2 天前的日期
DateTime twoDaysAgo = DateTime.Today.AddDays(-2);
然后在查詢中
smcNews = (from n in db.NewsShare
join e in db.CreateEmployee on n.Created_By equals e.Id join d in db.CreateDepartment on e.DepId equals d.Id
where n.CreatedDate > twoDaysAgo && n.CreatedDate <= DateTime.Today
select new NewsShareViewModel {
Id = n.Id,
UserName = e.EmpName,
Department = d.Department,
Message = n.Comment,
UserId = n.Created_By,
CreatedDate = n.CreatedDate.ToString()
}).ToList();
它不會回傳資料。我檢查了的值,twoDaysAgo就像{12/29/2021 12:00:00 AM}
中的資料CreatedDate是2021-12-31 13:43:19.957
所以我有什么方法可以通過從日期中洗掉時間或其他什么來獲得這個查詢?
uj5u.com熱心網友回復:
n.CreatedDate <= DateTime.Today是有效的n.CreatedDate <= 2021-12-31 00:00:00。
CreatedDate 中的資料是 2021-12-31 13:43:19.957
日期時間2021-12-31 13:43:19.957不是“小于或等于”2021-12-31 00:00:00
洗掉&& n.CreatedDate <= DateTime.Today 條件 - 它對您沒有任何作用(除了排除您今天創建的任何資料),假設將來無法創建記錄,并假設您希望創建自兩天前午夜以來的所有記錄
我有什么方法可以通過從日期中洗掉時間或其他什么來正確獲取此查詢?
盡可能避免這樣做;當您在某個范圍內搜索資料時,旨在始終使用從/到的一系列固定常數值。
不要在 Where 子句中操作表資料,除非您要創建不能使用索引的查詢(并因此成為性能問題)
uj5u.com熱心網友回復:
日期時間始終包含時間。你無法避免這一點。
如果您的開始日期是 29 日,這意味著您的Today值是午夜 31 日。2021-12-31 13:43:19.957是在午夜之后,所以它超出了您指定的范圍。
相反,使用第二天(午夜的第一天)作為上限。
DateTime start = DateTime.Today.AddDays(-2); //29th
DateTime end = DateTime.Today.AddDays(1); //1st
然后使用過濾:
where n.CreatedDate >= start && n.CreatedDate < end
使用注意事項>=和<。這確保包括 29 日、30 日和 31 日的所有內容;但從一開始就沒有。
uj5u.com熱心網友回復:
您將無法n.CreatedDate.Date與 EF一起使用。我猜您正在使用 .Net Framework 的 EF 版本,因為EF Core 支持 DateTime.Date
相反,您應該使用DbFunctions.TruncateTime.
DbFunctions.TruncateTime(n.CreatedDate) >= twoDaysAgo &&
DbFunctions.TruncateTime(n.CreatedDate) <= DateTime.Today
更新 - 不要這樣做 - 與正確排列查詢相比,它會相對較慢
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/407996.html
標籤:
下一篇:EntityFrameworkCoreAddMigration給出的值不能為空。dotnet中的(引數“connectionString”)
