gpt4 book ai didi

c# - 获取两次之间的记录列表 C# Linq To Entities

转载 作者:太空宇宙 更新时间:2023-11-03 21:00:24 25 4
gpt4 key购买 nike

在我的应用程序中,我想用数据库中符合特定条件的记录填充一个列表:

public ActionResult SelectYearGraph(int year)
{
var lstAllSummaries = db.Summaries.ToList();

var lstMonths =
lstAllSummaries.Where(x => x.FlightDay.Year == year)
.Select(x => x.TestDay.Month)
.Distinct()
.OrderBy(x => x)
.ToList();

List<string> lstMonthNames = new List<string>();
List<int> lstCountSummaries = new List<int>();
List<int> lstCountDailySummariesDifferentTime = new List<int>();

var tsSix = new TimeSpan(6, 0, 0);
var tsTen = new TimeSpan(22, 0, 0);

foreach (var item in lstMonths)
{
var monthName = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(item);
lstMonthNames.Add(monthName);
foreach (var item in lstMonths)
{
var monthName = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(item);
lstMonthNames.Add(monthName);
lstCountDailySummaries.Add(lstAllSummaries.Count(x => x.FlightDay.Month == item && x.FlightDay.Year == year
&& (x.FlightDay.TimeOfDay >= tsSix && x.FlightDay.TimeOfDay <= tsTen)
&& !x.deleted));
lstCountDailySummariesDifferentTime.Add(lstAllSummaries.Count(x => x.FlightDay.Month == item && x.FlightDay.Year == year
&& (x.FlightDay.TimeOfDay > tsTen || x.FlightDay.TimeOfDay < tsSix)
&& !x.deleted));
}
}
... // more down here but not relevant to question
}

当我运行它时,出现运行时错误:

The specified type member 'TimeOfDay' is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported.

我试过了Date and Time Canonical Functions for LINQ-to-Entities ,但我收到了同样的错误。

如何获取早上 6 点到晚上 10 点之间的所有记录?

最佳答案

您不需要 TimeOfDay 只需读取 DateTime 的 HourMinuteSecond 将为您提供相同的结果。

the TimeOfDay property returns a TimeSpan value that represents a DateTime value's time component.

所以只需将您的代码更改为:

...
&& (DbFunctions.CreateTime(x.TestDay.Hour, x.TestDay.Minute,x.TestDay.Second) > DbFunctions.CreateTime(6,0,0)
&& (DbFunctions.CreateTime(x.TestDay.Hour, x.TestDay.Minute, x.TestDay.Second) < DbFunctions.CreateTime(22,0,0))
...

寻找跨越午夜的时间的问题在于,虽然时间可以是早上 6 点之后和晚上 10 点之前,但晚上 10 点之后和早上 6 点之前就不是这样了。

您需要将 AND 更改为 OR

...
&& (
(DbFunctions.CreateTime(x.TestDay.Hour, x.TestDay.Minute,x.TestDay.Second) > DbFunctions.CreateTime(22,0,0)
|| (DbFunctions.CreateTime(x.TestDay.Hour, x.TestDay.Minute, x.TestDay.Second) < DbFunctions.CreateTime(6,0,0))
)
...

关于c# - 获取两次之间的记录列表 C# Linq To Entities,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46058147/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com