我有一个从数据库中提取数据的查询。它通过CheckDate对项目进行分组。我需要将CheckDate(标准日期时间)转换为月份,以便按月分组而不包含其他日期。我无法弄清楚如何做到这一点。
var query = from ech in this.dbContext.EmployeeCheckHistories
where ech.CompanyID == GlobalVariables.CompanyID &&
ech.Employees.ClientID == GlobalVariables.Client
group ech by ech.CheckDate into echG
orderby echG.Key descending
select echG;
答案 0 :(得分:1)
我需要将CheckDate作为标准DateTime转换为月份
如果确实是DateTime
,那么这应该可以解决问题。只需按CheckDate
上的Month属性进行分组。
var query = from ech in this.dbContext.EmployeeCheckHistories
where ech.CompanyID == GlobalVariables.CompanyID &&
ech.Employees.ClientID == GlobalVariables.Client
group ech by ech.CheckDate.Month into echG
orderby echG.Key descending
select echG;
如果它实际上是Nullable<DateTime>
,则需要检查该值是否存在,然后按月分组。
var query = from ech in this.dbContext.EmployeeCheckHistories
where ech.CompanyID == GlobalVariables.CompanyID &&
ech.Employees.ClientID == GlobalVariables.Client &&
ech.CheckDate.HasValue
group ech by ech.CheckDate.Value.Month into echG
orderby echG.Key descending
select echG;
答案 1 :(得分:0)
您的查询 -
var query = from ech in this.dbContext.EmployeeCheckHistories
where ech.CompanyID == GlobalVariables.CompanyID &&
ech.Employees.ClientID == GlobalVariables.Client
group ech by ech.CheckDate into echG
orderby echG.Key descending
select echG;
可以简化为 -
var query = this.dbContext.EmployeeCheckHistories.Where(c=>
c.CompanyID == GlobalVariable.CompanyID
&& c.Employees.ClientID == GlobalVariables.ClientID).GroupBy(d=> d.CheckDate.Month);