在我的应用程序中,我想用数据库中符合特定条件的记录填充列表:
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
}
当我运行它时,我收到运行时错误:
LINQ to Entities不支持指定的类型成员'TimeOfDay'。仅支持初始值设定项,实体成员和实体导航属性。
我尝试了Date and Time Canonical Functions for LINQ-to-Entities,但收到了同样的错误。
如何在早上6点到晚上10点之间获取所有记录?
答案 0 :(得分:3)
您不需要TimeOfDay
只需阅读Hour
Minute
,Second
DateTime
即可在您的情况下获得相同的结果
TimeOfDay属性返回TimeSpan值,该值表示DateTime值的时间组件。
所以只需将您的代码更改为:
...
&& (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))
)
...
答案 1 :(得分:1)
var query = from x in db.Summaries
let time = DbFunctions.CreateTime(x.TestDay.Hour, x.TestDay.Minute, x.TestDay.Second)
where x.FlightDay.Year == year
&& !x.deleted
&& (time < DbFunctions.CreateTime(6, 0, 0))
&& (time > DbFunctions.CreateTime(22, 0, 0))
group x by x.FlightDay.Month into summaries
let month = summaries.Key
select new
{
Month = month,
Count = summaries.Count(),
DifferentCount = (from d in db.DailySummaries
let timed = DbFunctions.CreateTime(d.TestDay.Hour, d.TestDay.Minute, d.TestDay.Second)
where d.FlightDay.Year == year && d.FlightDay.Month == month
&& !d.deleted
&& (timed < DbFunctions.CreateTime(6, 0, 0))
&& (timed > DbFunctions.CreateTime(22, 0, 0))
select d).Count(),
};