c# - Entity Framework 中的分组和计数

标签 c# entity-framework linq-to-entities count

我有一个包含日志的表格,我按如下方式计算每天的日志:

// Count logs by day
IList<DataModel> models = _context.Logs
  .Where(x => x.Created >= dateMinimum && x.Created <= dateMaximum)
  .GroupBy(x => new { Year = x.Created.Year, Month = x.Created.Month, Day = x.Created.Day })
  .Select(x => new { Year = x.Key.Year, Month = x.Key.Month, Day = x.Key.Day, Count = x.Count() })
  .AsEnumerable()
  .Select(x => new DataModel { Date = new DateTime(x.Year, x.Month, x.Day), LogsCount = x.Count })
  .ToList();

// Fill empty days with dates which contains all days in range
models.AddRange(dates.Where(x => !models.Any(y => y.Date == x.Date)).Select(x => new DataModel { Date = x, LogsCount = 0 }));

如果我想独立于类型按天计算所有日志,这是可行的。

但我想按日期和类型(错误、警告、信息...)计算日志。

我尝试将 x.Type 添加到组中,但最后我只得到 3 个项目。

目前我的数据模型如下:

public class DataModel
{
    public DateTime Date { get; set; }
    public Int32 LogsCount { get; set; }
}

但也许它应该是这样的:

public class DataModel
{
    public DateTime Date { get; set; }
    public KeyValuePair<String, Int32> LogsCount { get; set; }
}

其中 LogsCount 有一个包含类型的字符串和包含计数的 Int32。

我该怎么做?

最佳答案

可能要考虑使用 entity functions用于按日期分组。

例子:

var results = query.GroupBy(r => new
{
    SentDate = System.Data.Objects.EntityFunctions.TruncateTime(r.Launch.EmailDeliveredDate),
    EventSubTypeID = r.EmailEventSubtypeID
})
.Select(x => new
{
    x.Key.SentDate,
    x.Key.EventSubTypeID,
    NumResults = x.Count()
})
.ToList();

关于c# - Entity Framework 中的分组和计数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13012472/

相关文章:

c# - 使用 Linq to Entities 查询创建 null ienumerable

c# - 在关闭表格时开始新表格。 C#

c# - 使用 rijndael 加密

c# - Access 数据库上的更新查询不工作 C#.NET

c# - 我应该始终在 N 层 MVC 应用程序中使用 AsNoTracking 吗?

c# - 如何使用 Oracle Entity Framework 支持强制使用 pascal 大小写?

c# - LinqTo 实体中的日期部分相等

c# - 对 Sql Server 中的索引感到困惑

c# - 如何确定 Entity Framework 对象是否已更改?

c# - linq搜索法语字符