我对Entity Framework不好,因此计划运行原始查询。现在,我被卡住了。使用以下代码时,出现以下错误。
错误CS1061“响应”不包含“ TotalCount”的定义,并且 没有扩展方法'Total'接受类型的第一个参数 可以找到“响应”(您是否缺少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);
}
答案 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)