【问题标题】:Running SqlQuery to count rows by date运行 Sql Query 按日期计算行数
【发布时间】:2019-01-26 07:43:33
【问题描述】:

我不擅长实体框架,但计划运行原始查询。现在我被困住了。使用以下代码时,出现以下错误。

错误 CS1061 'Respons' 不包含 'TotalCount' 的定义和 没有扩展方法“总计”接受类型的第一个参数 可以找到“响应”(您是否缺少 using 指令或 汇编参考?)

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

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

【问题讨论】:

  • 错误很清楚:您的类Respons 不包含属性TotalCount - 所以即使您的SQL 可能返回该值,周围也没有属性实际存储它。因此,当您遍历所有返回的数据时 - 如果您的类 Respons 不包含任何属性,您如何想象总计数会显示出来?!?!?!?

标签: entity-framework-5


【解决方案1】:

首先创建一个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");

【讨论】:

    【解决方案2】:

    嗯,从消息中可以清楚地看出您的班级缺少“总计数”属性。

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

    LINQ GroupBy translation

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-02-09
      • 1970-01-01
      • 2021-05-06
      • 1970-01-01
      • 2017-03-25
      • 1970-01-01
      • 2020-09-17
      相关资源
      最近更新 更多