集团与实体框架计数 [英] Group and Count in Entity Framework

查看:93
本文介绍了集团与实体框架计数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有记录的表,我指望每天的日志如下:

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, ...).

我。试图x.Type添加到组,但最后我得到的只有3项

I tried to add x.Type to group but at the end I get only 3 items.

目前我的DataModel如下:

At the moment my DataModel is the following:

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



在哪里LogsCount有持有类型的字符串和的Int32其中包含数

Where LogsCount has a string which holds the Type and Int32 which contains the count.

我怎样才能做到这一点?

How can I do this?

推荐答案

可能要考虑使用实体的功能的按日期分组。

Might want to consider using entity functions for grouping by date.

例如:

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

这篇关于集团与实体框架计数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆