如何在实体框架和ASP.NET MVC中使用groupby子句并获取计数

问题描述

我有一个聊天模型类,如下:

public class Chat
    {
        [Key]
        public int ChatId { get; set; }

        [required]
        public string CustName { get; set; }


        public string Query { get; set; }

        public string Resolution { get; set; }

        public string Region { get; set; }

        [required]
        public DateTime ChatStartDateTime { get; set; }

        public DateTime? ChatCreateDateTime { get; set; }

        public DateTime? ChatEndDateTime { get; set; }

        public string Feedback { get; set; }

        public DateTime? FeedbackDateTime { get; set; }

        public string FeedbacksharedBy { get; set; }

        public int Id { get; set; }
        public string Username { get; set; }
        public string FirstName { get; set; }
        public string Email { get; set; }
        public string DidCustCreateTicket { get; set; }

        [EmailAddress(ErrorMessage = "Invalid Email Address")]
        public string Custemail { get; set; }

        public int? ScenarioId { get; set; }
        public string ScenarioList { get; set; }


        [ForeignKey("Id")]
        public virtual User User { get; set; }

        [ForeignKey("ScenarioId")]
        public virtual Scenario Scenario { get; set; }

        public IEnumerable<SelectListItem> Scenarios {get;set;}

        public IEnumerable<SelectListItem> Users { get; set; }

    }

我想获取“聊天”报告,以便在“工具”中添加了多少个聊天,并按“情景”将其分组,并仅显示“情景总计数”。

例如:

TOtal Chats Count groupby Scenario

这是我尝试过但不知道自己在做什么的查询

public ActionResult test()
        {
            using (Db db = new Db())
            {
                ViewBag.resultset = db.Chats
            .Where(x => System.Data.Entity.DbFunctions.TruncateTime(x.ChatCreateDateTime) == DateTime.Today)
            .GroupBy(ddda => ddda.Scenario)
            .ToList()
            .Select(s => new
            {
                //month = CultureInfo.CurrentCulture.DateTimeFormat.GetMonthName(s.Key),count = s.Count()
            });

                return View();
            }
        }

非常感谢您的帮助

解决方法

通过创建另一个具有2个已设置属性ScenarioName和Count的VM类作为ScenarioVM来解决该问题,并将其用于实际的查询中。让我知道是否有人需要帮助