Linq to Entity Group by Date

时间:2011-03-25 22:38:55

标签: c# linq linq-to-entities

做了很多研究,但仍然有一个艰难的研究。考虑具有“CreatedOn”,“Amount”,“Type”的事务表的数据库。我需要能够进行实体查询以获得按不同日期粒度(月/日等)组合在一起的特定类型的事务。

想象一下一张表:

2011/1/22   $300   Deposit
2011/2/18   $340   Deposit
2011/3/6   $200    Other
2011/3/6   $100    Deposit
2011/3/7   $50     Deposit

我可以有一个查询,它会按月分组所有存款,以便它可以产生:

2011-1 $300 1deposit
2011-2 $340 1deposit
2011-3 $150 2deposits

我如何将此查询调整为按天而不是按月计算?

这是我当前的代码块,但是我得到了一个内部linq异常

  

无法在A1上分组

var result = context.TransactionEntities.Where(d => d.Type == "Deposit")                                     
                    .GroupBy(g => new { g.CreatedOn.Year, g.CreatedOn.Month })
                    .Select(g => new
                           {
                                 DateKey = g.Key,
                                 TotalDepositAmount = g.Sum(d => d.Amount),
                                 DepositCount = g.Count()
                            }).ToList();

注意:我目前正在使用MySql连接器,我读过这可能是一个错误?

3 个答案:

答案 0 :(得分:1)

Func<DateTime, object> groupByClause;
if (groupByDay) groupByClause = date => date.Date;
else if (groupByMonth) groupByClause = date => new { date.Year, date.Month};
else throw new NotSupportedException("Some option should be chosen");

var result = data.Where(d => d.Type == "Deposit")
                 .GroupBy(groupByClause)
                 .Select(g => new { DateKey = g.Key,
                                    TotalDepositAmount = g.Sum(d => d.Amount),
                                    DepositCount = g.Count(),
                 });

当然应检查linq-2-entities是否接受它。

答案 1 :(得分:0)

检查我的问题中提到的代码:Group by Weeks in LINQ to Entities。它显示了如何按天和月分组数据。如果您有任何其他问题,请与我们联系。

答案 2 :(得分:0)

这可能是MySQL连接器中的一个错误。我的解决方案是在.ToList()之前放置.GroupBy()

相关问题