我面臨的問題是要知道 DateTime 是否在 dotnet 中的日期范圍之間。
例如,如果 x.SchedulerStart 值為2022-11-02 06:46:30并且 x.SchedulerEnd 值為2022-11-02 23:26:30。我想檢查這個 DateTime.Today 值是否在日期范圍內,但下面的編碼不起作用。我看過這個 StackOverflow 問題仍然無法作業如何知道 DateTime 是否在 C# 中的 DateRange 之間
下面是我的編碼:
x.SchedulerStart.Date >= DateTime.Today && x.SchedulerEnd.Date <= DateTime.Today
整個代碼:
List<SAASMsgSchedulerForQueueList> msgSchedulerList = await _saasdbContext.SaMsgScheduler.AsNoTracking().Where(x => (x.Enabled == true && x.SchedulerStart.Date >= DateTime.Today && x.SchedulerEnd.Date <= DateTime.Today) &&
((x.SchedulerRecurring == "Daily" && x.RecurringTime == currentTime) || (x.SchedulerRecurring == "Weekly" && x.RecurringWeekday == weekDayNumber && x.RecurringTime == currentTime) ||
(x.SchedulerRecurring == "Monthly" && x.RecurringDay == currentDay && x.RecurringTime == currentTime) || (x.SchedulerRecurring == "Yearly" && x.RecurringMonth == currentMonth && x.RecurringTime == currentTime)))
.Join(_saasdbContext.TnMsgTemplate.AsNoTracking(),
schedule => schedule.TemplateId,
template => template.Id,
(schedule, template) => new { schedule, template })
.Join(_saasdbContext.SaMsgQuery.AsNoTracking(),
schedule => schedule.template.QueryId,
query => query.Id,
(schedule, query) => new SAASMsgSchedulerForQueueList()
{
ID = schedule.schedule.Id,
BranchID = schedule.schedule.BranchId,
TemplateID = schedule.schedule.TemplateId,
TemplateContent = schedule.template.TemplateContent,
Query = query.QuerySql,
MessageType = schedule.schedule.MessageType,
RecurringDatetime = schedule.schedule.RecurringDatetime,
}).ToListAsync();
希望有人可以指導我如何解決這個問題。謝謝。
uj5u.com熱心網友回復:
你需要扭轉這種情況。現在,您正在尋找今天之后開始并在今天之前結束的東西。
最好以反映您想要的形式撰寫查詢,即今天介于開始日期和結束日期之間:
x.SchedulerStart.Date <= DateTime.Today && DateTime.Today <= x.SchedulerEnd.Date
更好的是,在 20 年后,如果我將欄位放在此類查詢的左側,我仍然會混淆。不必翻譯一個運算式來理解它的作用
另一個改進是避免.Date。這將導致在cast(ScheduleStart as date)SQL Server 中。通常這樣的強制轉換會阻止索引的使用。SQL Server 足夠聰明,可以將其轉換為范圍查詢,但不能使用為該ScheduleStart列收集的任何索引,并且仍然會導致執行計劃效率低下。
.Date可以簡單地從中洗掉DateTime.Today <= x.SchedulerEnd.Date。如果結束日期是今天,則DateTime.Today <= x.SchedulerEnd無論何時都保持。
要從開盤日期中消除.Date,請將其與第二天進行比較,即x.SchedulerStart < DateTime.Today.AddDays(1)。如果開始日是今天,則每次都會如此。如果SchedulerStart在第二天,條件仍然為假。
一個正確有效的條件是:
x.SchedulerStart < DateTime.Today.AddDays(1)
&& DateTime.Today <= x.SchedulerEnd
該查詢使用 Oracle 的官方 EF Core 提供程式MySQL.EntityFrameworkCore以 MySQL 為目標,它有幾個已知問題,這些問題已按照 Oracle 自己的計劃進行修復。這就是為什么幾乎每個人都使用真正開源的Pomelo.EntityFrameworkCore.MySql。Pomelo 下載量為 2930 萬,甲骨文供應商下載量為 170 萬。
在這種情況下,Oracle 的提供程式未能將DateTime.Today.AddDays(1)其視為常量并嘗試將其轉換為 SQL 運算式。
為避免此問題,請在查詢之前計算日期,例如:
var today = DateTime.Today;
var tomorrow = today.AddDays(1);
...
x.SchedulerStart < tomorrow && today <= x.SchedulerEnd
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/525622.html
上一篇:使用檢查器拖放參考有什么缺點嗎?
下一篇:具有一對多導航屬性中的記錄數
