简体   繁体   English

实体框架中的组和计数

[英]Group and Count in Entity Framework

I have a table with Logs and I am counting the Logs per day as follows: 我有一个日志表,我按如下方式计算每日日志:

// 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 }));

This is working if I want to count all logs by day independently of the type. 如果我想按天计算所有日志而不考虑类型,这是有效的。

But I would like to count logs by day and type (Error, Warn, Info, ...). 但我想按日计算日志并输入(错误,警告,信息......)。

I tried to add x.Type to group but at the end I get only 3 items. 我试图将x.Type添加到组,但最后我只得到3个项目。

At the moment my DataModel is the following: 目前我的DataModel如下:

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

But maybe it should be something like: 但也许它应该是这样的:

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

Where LogsCount has a string which holds the Type and Int32 which contains the count. 其中LogsCount有一个字符串,其中包含Type和Int32,其中包含计数。

How can I do this? 我怎样才能做到这一点?

Might want to consider using entity functions for grouping by date. 可能要考虑使用实体函数按日期分组。

Example: 例:

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();

Did you try something like this? 你尝试过这样的事吗?

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


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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM