我想过滤今天,周和月的数据。
var data = new DashboardViewModel()
{
Today = new State() { Download = db.Download.Where(x => x.Time == DateTime.Today).Count(), Visit = db.Visit.Where(x => x.Time == DateTime.Today).Count() },
Week = new State() { Download = db.Download.Where(x => x.Time.DayOfYear <= Day && x.Time.DayOfYear >= Day - 7).Count(), Visit = db.Visit.Where(x => x.Time.DayOfYear <= Day && x.Time.DayOfYear >= Day - 7).Count() },
Month = new State() { Download = db.Download.Where(x => x.Time.DayOfYear <= Day && x.Time.DayOfYear >= Day - 30).Count(), Visit = db.Visit.Where(x => x.Time.DayOfYear <= Day && x.Time.DayOfYear >= Day - 30).Count() },
Total = new State() { Download=db.Download.Count(),Visit=db.Visit.Count()}
};
它给出错误:
LINQ to Entities不支持指定的类型成员'DayOfYear'。
如何解决此错误,还是有其他更好的方法可以解决此问题?
答案 0 :(得分:2)
问题在于,当LINQ to Entities解析你的lambda表达式并将其转换为SQL时,它不知道'DayOfYear'是什么,以及它如何映射到有效的SQL。这是DbFunctions(v6之前的EF EntityFunctions)的来源,它允许您在LINQ to Entities中使用日期操作函数。例如,要按周过滤,您可以使用:
Week = new State() {
Download = db.Download.Where(x => DbFunctions.DiffDays(DbFunctions.TruncateTime(x.Time), Day) <= 7).Count(),
Visit = db.Visit.Where(x => DbFunctions.DiffDays(DbFunctions.TruncateTime(x.Time), Day) <= 7).Count() }
TruncateTime从日期中删除时间组件,DiffDays(d1,d2)为您提供2天(d2 - d1)之间的差异。
答案 1 :(得分:1)
请参阅此answer:
var ruleDate = Convert.ToDateTime(rule.data).Date;
return jobdescriptions.Where(j.Deadline.Year == ruleDate.Year
&& j j.Deadline.Month == ruleDate.Month
&& j.Deadline.Day == ruleDate.Day);