运行SqlQuery按日期对行进行计数

时间:2019-01-26 07:43:33

标签: entity-framework-5

我对Entity Framework不好,因此计划运行原始查询。现在,我被卡住了。使用以下代码时,出现以下错误。

  

错误CS1061“响应”不包含“ TotalCount”的定义,并且   没有扩展方法'Total'接受类型的第一个参数   可以找到“响应”(您是否缺少using指令或   程序集参考?)

当我在SSMS中运行相同的查询时,我得到以下结果。

enter image description here

Respons.cs

namespace Survey.Models
{
    using System;
    using System.Collections.Generic;

    public partial class Respons
    {
        public int ResponseID { get; set; }
        public string Username { get; set; }
        public string Name { get; set; }
        public string EmailAddress { get; set; }
        public Nullable<System.DateTime> DateTime { get; set; }
    }
}

原始查询

DbSqlQuery<Respons> Responses = DbContext.Responses.SqlQuery("SELECT max(ResponseID) AS ResponseID, COUNT(CreatedDateTime) AS Total, MAX(FORMAT(CreatedDateTime, 'dd-MMM-yyyy', 'en-US' )) as Date FROM Responses GROUP BY CAST(CreatedDateTime AS DATE) ORDER BY Date DESC");
foreach ( var r in Responses ){
   Response.Write( r.TotalCount);
}

2 个答案:

答案 0 :(得分:2)

首先按如下所示制作一个ViewModel类:

public class TotalCountByDateViewModel
{
   public int TotalCount { get; set; }
   public string Date { get; set; }
}

现在按如下所示编写查询:

DbSqlQuery<TotalCountByDateViewModel> totalCountsByDate = DbContext.Responses
  .SqlQuery("SELECT max(ResponseID) AS ResponseID, COUNT(CreatedDateTime)
  AS Total, MAX(FORMAT(CreatedDateTime, 'dd-MMM-yyyy', 'en-US' ))
  as Date FROM Responses GROUP BY CAST(CreatedDateTime AS DATE) ORDER BY Date DESC");

答案 1 :(得分:1)

好吧,从消息中可以很清楚地看到您的班级缺少“总计”属性。

如何按查询编写分组参考此链接:

LINQ GroupBy translation